id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
36,600
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/SqlExecutor.java
SqlExecutor.fillIdentityPrimaryKeys
@SuppressWarnings("unchecked") protected void fillIdentityPrimaryKeys(Object entity, ResultSet rs) throws SQLException { BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass()); int size = beanDesc.getPropertyDescSize(); for(int i=0; i < size; i++){ PropertyDesc propertyDesc = beanDesc.getPropertyDesc(i); PrimaryKey primaryKey = propertyDesc.getAnnotation(PrimaryKey.class); if(primaryKey != null && primaryKey.generationType() == GenerationType.IDENTITY){ if(rs.next()){ Class<?> propertyType = propertyDesc.getPropertyType(); @SuppressWarnings("rawtypes") ValueType valueType = MirageUtil.getValueType(propertyType, propertyDesc, dialect, valueTypes); if(valueType != null){ propertyDesc.setValue(entity, valueType.get(propertyType, rs, 1)); } } } } }
java
@SuppressWarnings("unchecked") protected void fillIdentityPrimaryKeys(Object entity, ResultSet rs) throws SQLException { BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass()); int size = beanDesc.getPropertyDescSize(); for(int i=0; i < size; i++){ PropertyDesc propertyDesc = beanDesc.getPropertyDesc(i); PrimaryKey primaryKey = propertyDesc.getAnnotation(PrimaryKey.class); if(primaryKey != null && primaryKey.generationType() == GenerationType.IDENTITY){ if(rs.next()){ Class<?> propertyType = propertyDesc.getPropertyType(); @SuppressWarnings("rawtypes") ValueType valueType = MirageUtil.getValueType(propertyType, propertyDesc, dialect, valueTypes); if(valueType != null){ propertyDesc.setValue(entity, valueType.get(propertyType, rs, 1)); } } } } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "void", "fillIdentityPrimaryKeys", "(", "Object", "entity", ",", "ResultSet", "rs", ")", "throws", "SQLException", "{", "BeanDesc", "beanDesc", "=", "beanDescFactory", ".", "getBeanDesc", "(", "entity"...
Sets GenerationType.IDENTITY properties value. @param entity the entity @param rs the result set @throws SQLException if something goes wrong.
[ "Sets", "GenerationType", ".", "IDENTITY", "properties", "value", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/SqlExecutor.java#L437-L457
36,601
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/util/MirageUtil.java
MirageUtil.buildDeleteSql
public static String buildDeleteSql(BeanDescFactory beanDescFactory, EntityOperator entityOperator, Class<?> entityType, NameConverter nameConverter, List<PropertyDesc> propDescs){ StringBuilder sb = new StringBuilder(); sb.append("DELETE FROM ").append(getTableName(entityType, nameConverter)); sb.append(" WHERE "); boolean hasPrimaryKey = false; BeanDesc beanDesc = beanDescFactory.getBeanDesc(entityType); for(int i=0;i<beanDesc.getPropertyDescSize();i++){ PropertyDesc pd = beanDesc.getPropertyDesc(i); PrimaryKeyInfo primaryKey = entityOperator.getPrimaryKeyInfo(entityType, pd, nameConverter); if(primaryKey != null && pd.isReadable()){ if(!propDescs.isEmpty()){ sb.append(" AND "); } sb.append(getColumnName(entityOperator, entityType, pd, nameConverter)).append(" = ?"); propDescs.add(pd); hasPrimaryKey = true; } } if(hasPrimaryKey == false){ throw new RuntimeException( "Primary key is not found: " + entityType.getName()); } return sb.toString(); }
java
public static String buildDeleteSql(BeanDescFactory beanDescFactory, EntityOperator entityOperator, Class<?> entityType, NameConverter nameConverter, List<PropertyDesc> propDescs){ StringBuilder sb = new StringBuilder(); sb.append("DELETE FROM ").append(getTableName(entityType, nameConverter)); sb.append(" WHERE "); boolean hasPrimaryKey = false; BeanDesc beanDesc = beanDescFactory.getBeanDesc(entityType); for(int i=0;i<beanDesc.getPropertyDescSize();i++){ PropertyDesc pd = beanDesc.getPropertyDesc(i); PrimaryKeyInfo primaryKey = entityOperator.getPrimaryKeyInfo(entityType, pd, nameConverter); if(primaryKey != null && pd.isReadable()){ if(!propDescs.isEmpty()){ sb.append(" AND "); } sb.append(getColumnName(entityOperator, entityType, pd, nameConverter)).append(" = ?"); propDescs.add(pd); hasPrimaryKey = true; } } if(hasPrimaryKey == false){ throw new RuntimeException( "Primary key is not found: " + entityType.getName()); } return sb.toString(); }
[ "public", "static", "String", "buildDeleteSql", "(", "BeanDescFactory", "beanDescFactory", ",", "EntityOperator", "entityOperator", ",", "Class", "<", "?", ">", "entityType", ",", "NameConverter", "nameConverter", ",", "List", "<", "PropertyDesc", ">", "propDescs", ...
Builds delete SQL and correct parameters from the entity. @param beanDescFactory the bean descriptor factory @param entityOperator the entity operator @param entityType the entity class to delete @param nameConverter the name converter @param propDescs the list of parameters @return Delete SQL @deprecated use {@link #buildDeleteSql(String, BeanDescFactory, EntityOperator, Object, NameConverter, List)} instead
[ "Builds", "delete", "SQL", "and", "correct", "parameters", "from", "the", "entity", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/util/MirageUtil.java#L458-L487
36,602
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/SqlManagerImpl.java
SqlManagerImpl.fillPrimaryKeysBySequence
private void fillPrimaryKeysBySequence(Object entity){ if(!dialect.supportsGenerationType(GenerationType.SEQUENCE)){ return; } BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass()); int size = beanDesc.getPropertyDescSize(); for(int i=0; i < size; i++){ PropertyDesc propertyDesc = beanDesc.getPropertyDesc(i); PrimaryKey primaryKey = propertyDesc.getAnnotation(PrimaryKey.class); if(primaryKey != null && primaryKey.generationType() == GenerationType.SEQUENCE){ String sql = dialect.getSequenceSql(primaryKey.generator()); Object value = sqlExecutor.getSingleResult(propertyDesc.getPropertyType(), sql, new Object[0]); propertyDesc.setValue(entity, value); } } }
java
private void fillPrimaryKeysBySequence(Object entity){ if(!dialect.supportsGenerationType(GenerationType.SEQUENCE)){ return; } BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass()); int size = beanDesc.getPropertyDescSize(); for(int i=0; i < size; i++){ PropertyDesc propertyDesc = beanDesc.getPropertyDesc(i); PrimaryKey primaryKey = propertyDesc.getAnnotation(PrimaryKey.class); if(primaryKey != null && primaryKey.generationType() == GenerationType.SEQUENCE){ String sql = dialect.getSequenceSql(primaryKey.generator()); Object value = sqlExecutor.getSingleResult(propertyDesc.getPropertyType(), sql, new Object[0]); propertyDesc.setValue(entity, value); } } }
[ "private", "void", "fillPrimaryKeysBySequence", "(", "Object", "entity", ")", "{", "if", "(", "!", "dialect", ".", "supportsGenerationType", "(", "GenerationType", ".", "SEQUENCE", ")", ")", "{", "return", ";", "}", "BeanDesc", "beanDesc", "=", "beanDescFactory"...
Sets GenerationType.SEQUENCE properties value.
[ "Sets", "GenerationType", ".", "SEQUENCE", "properties", "value", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/SqlManagerImpl.java#L329-L347
36,603
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/SqlManagerImpl.java
SqlManagerImpl.setValueTypes
public void setValueTypes(List<ValueType<?>> valueTypes) { Validate.noNullElements(valueTypes); this.sqlExecutor.setValueTypes(valueTypes); this.callExecutor.setValueTypes(valueTypes); }
java
public void setValueTypes(List<ValueType<?>> valueTypes) { Validate.noNullElements(valueTypes); this.sqlExecutor.setValueTypes(valueTypes); this.callExecutor.setValueTypes(valueTypes); }
[ "public", "void", "setValueTypes", "(", "List", "<", "ValueType", "<", "?", ">", ">", "valueTypes", ")", "{", "Validate", ".", "noNullElements", "(", "valueTypes", ")", ";", "this", ".", "sqlExecutor", ".", "setValueTypes", "(", "valueTypes", ")", ";", "th...
Sets the value types. @param valueTypes the value types to set. @throws IllegalArgumentException if the {@code valueTypes} is {@code null} or an element in the {@code valueTypes} is {@code null}
[ "Sets", "the", "value", "types", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/SqlManagerImpl.java#L539-L543
36,604
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/updater/SchemaUpdater.java
SchemaUpdater.getSql
protected String getSql(int version){ Dialect dialect = ((SqlManagerImpl) sqlManager).getDialect(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream in = classLoader.getResourceAsStream( String.format("%s/%s_%d.sql", packageName, dialect.getName().toLowerCase(), version)); if(in == null){ in = classLoader.getResourceAsStream( String.format("%s/%d.sql", packageName, version)); if(in == null){ return null; } } byte[] buf = IOUtil.readStream(in); return new String(buf, StandardCharsets.UTF_8); }
java
protected String getSql(int version){ Dialect dialect = ((SqlManagerImpl) sqlManager).getDialect(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream in = classLoader.getResourceAsStream( String.format("%s/%s_%d.sql", packageName, dialect.getName().toLowerCase(), version)); if(in == null){ in = classLoader.getResourceAsStream( String.format("%s/%d.sql", packageName, version)); if(in == null){ return null; } } byte[] buf = IOUtil.readStream(in); return new String(buf, StandardCharsets.UTF_8); }
[ "protected", "String", "getSql", "(", "int", "version", ")", "{", "Dialect", "dialect", "=", "(", "(", "SqlManagerImpl", ")", "sqlManager", ")", ".", "getDialect", "(", ")", ";", "ClassLoader", "classLoader", "=", "Thread", ".", "currentThread", "(", ")", ...
Returns the SQL which located within a package specified by the packageName as "dialectname_version.sql" or "version.sql". @param version the version number @return SQL or null if the SQL file does not exist
[ "Returns", "the", "SQL", "which", "located", "within", "a", "package", "specified", "by", "the", "packageName", "as", "dialectname_version", ".", "sql", "or", "version", ".", "sql", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/updater/SchemaUpdater.java#L117-L136
36,605
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/updater/SchemaUpdater.java
SchemaUpdater.existsTable
protected boolean existsTable(){ try { int count = sqlManager.getSingleResult(Integer.class, new StringSqlResource(String.format("SELECT COUNT(*) FROM %s", tableName))); if(count == 0){ // TODO Should insert an initial record? return false; } return true; } catch(SQLRuntimeException ex){ return false; } }
java
protected boolean existsTable(){ try { int count = sqlManager.getSingleResult(Integer.class, new StringSqlResource(String.format("SELECT COUNT(*) FROM %s", tableName))); if(count == 0){ // TODO Should insert an initial record? return false; } return true; } catch(SQLRuntimeException ex){ return false; } }
[ "protected", "boolean", "existsTable", "(", ")", "{", "try", "{", "int", "count", "=", "sqlManager", ".", "getSingleResult", "(", "Integer", ".", "class", ",", "new", "StringSqlResource", "(", "String", ".", "format", "(", "\"SELECT COUNT(*) FROM %s\"", ",", "...
Checks the table which manages a schema version exists or not exists. @return if the table exists then returns true; otherwise false
[ "Checks", "the", "table", "which", "manages", "a", "schema", "version", "exists", "or", "not", "exists", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/updater/SchemaUpdater.java#L143-L157
36,606
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/updater/SchemaUpdater.java
SchemaUpdater.createTable
protected void createTable(){ sqlManager.executeUpdate( new StringSqlResource(String.format("CREATE TABLE %s (VERSION NUMERIC NOT NULL)", tableName))); sqlManager.executeUpdate( new StringSqlResource(String.format("INSERT INTO %s (0))", tableName))); }
java
protected void createTable(){ sqlManager.executeUpdate( new StringSqlResource(String.format("CREATE TABLE %s (VERSION NUMERIC NOT NULL)", tableName))); sqlManager.executeUpdate( new StringSqlResource(String.format("INSERT INTO %s (0))", tableName))); }
[ "protected", "void", "createTable", "(", ")", "{", "sqlManager", ".", "executeUpdate", "(", "new", "StringSqlResource", "(", "String", ".", "format", "(", "\"CREATE TABLE %s (VERSION NUMERIC NOT NULL)\"", ",", "tableName", ")", ")", ")", ";", "sqlManager", ".", "e...
Creates table which manages schema version and insert an initial record as version 0.
[ "Creates", "table", "which", "manages", "schema", "version", "and", "insert", "an", "initial", "record", "as", "version", "0", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/updater/SchemaUpdater.java#L162-L168
36,607
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/session/SessionFactory.java
SessionFactory.getSession
public synchronized static Session getSession() { if(session == null){ Properties properties = IOUtil.loadProperties("jdbc.properties"); session = getSession(properties); } return session; }
java
public synchronized static Session getSession() { if(session == null){ Properties properties = IOUtil.loadProperties("jdbc.properties"); session = getSession(properties); } return session; }
[ "public", "synchronized", "static", "Session", "getSession", "(", ")", "{", "if", "(", "session", "==", "null", ")", "{", "Properties", "properties", "=", "IOUtil", ".", "loadProperties", "(", "\"jdbc.properties\"", ")", ";", "session", "=", "getSession", "(",...
Returns a session configured with the properties specified in the "jdbc.properties" file. @return {@link Session} @throws ConfigurationException if the configuration can't be loaded
[ "Returns", "a", "session", "configured", "with", "the", "properties", "specified", "in", "the", "jdbc", ".", "properties", "file", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/session/SessionFactory.java#L22-L29
36,608
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/naming/Inflection.java
Inflection.isUncountable
public static boolean isUncountable(String word) { for (String w : UNCOUNTABLE) { if (w.equalsIgnoreCase(word)) { return true; } } return false; }
java
public static boolean isUncountable(String word) { for (String w : UNCOUNTABLE) { if (w.equalsIgnoreCase(word)) { return true; } } return false; }
[ "public", "static", "boolean", "isUncountable", "(", "String", "word", ")", "{", "for", "(", "String", "w", ":", "UNCOUNTABLE", ")", "{", "if", "(", "w", ".", "equalsIgnoreCase", "(", "word", ")", ")", "{", "return", "true", ";", "}", "}", "return", ...
Return true if the word is uncountable. @param word The word @return True if it is uncountable
[ "Return", "true", "if", "the", "word", "is", "uncountable", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/naming/Inflection.java#L115-L122
36,609
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/naming/Inflection.java
Inflection.singularize
public static String singularize(String word) { if (isUncountable(word)) { return word; } else { for (Inflection inflection : SINGULAR) { if (inflection.match(word)) { return inflection.replace(word); } } } return word; }
java
public static String singularize(String word) { if (isUncountable(word)) { return word; } else { for (Inflection inflection : SINGULAR) { if (inflection.match(word)) { return inflection.replace(word); } } } return word; }
[ "public", "static", "String", "singularize", "(", "String", "word", ")", "{", "if", "(", "isUncountable", "(", "word", ")", ")", "{", "return", "word", ";", "}", "else", "{", "for", "(", "Inflection", "inflection", ":", "SINGULAR", ")", "{", "if", "(",...
Return the singularized version of a word. @param word The word @return The singularized word
[ "Return", "the", "singularized", "version", "of", "a", "word", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/naming/Inflection.java#L149-L160
36,610
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/naming/Inflection.java
Inflection.match
public boolean match(String word) { int flags = 0; if (ignoreCase) { flags = flags | Pattern.CASE_INSENSITIVE; } return Pattern.compile(pattern, flags).matcher(word).find(); }
java
public boolean match(String word) { int flags = 0; if (ignoreCase) { flags = flags | Pattern.CASE_INSENSITIVE; } return Pattern.compile(pattern, flags).matcher(word).find(); }
[ "public", "boolean", "match", "(", "String", "word", ")", "{", "int", "flags", "=", "0", ";", "if", "(", "ignoreCase", ")", "{", "flags", "=", "flags", "|", "Pattern", ".", "CASE_INSENSITIVE", ";", "}", "return", "Pattern", ".", "compile", "(", "patter...
Does the given word match? @param word The word @return True if it matches the inflection pattern
[ "Does", "the", "given", "word", "match?" ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/naming/Inflection.java#L207-L213
36,611
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/naming/Inflection.java
Inflection.replace
public String replace(String word) { int flags = 0; if (ignoreCase) { flags = flags | Pattern.CASE_INSENSITIVE; } return Pattern.compile(pattern, flags).matcher(word).replaceAll(replacement); }
java
public String replace(String word) { int flags = 0; if (ignoreCase) { flags = flags | Pattern.CASE_INSENSITIVE; } return Pattern.compile(pattern, flags).matcher(word).replaceAll(replacement); }
[ "public", "String", "replace", "(", "String", "word", ")", "{", "int", "flags", "=", "0", ";", "if", "(", "ignoreCase", ")", "{", "flags", "=", "flags", "|", "Pattern", ".", "CASE_INSENSITIVE", ";", "}", "return", "Pattern", ".", "compile", "(", "patte...
Replace the word with its pattern. @param word The word @return The result
[ "Replace", "the", "word", "with", "its", "pattern", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/naming/Inflection.java#L221-L227
36,612
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/session/DialectAutoSelector.java
DialectAutoSelector.getDialect
public static Dialect getDialect(String url){ if(url.startsWith("jdbc:mysql:")){ return new MySQLDialect(); } else if(url.startsWith("jdbc:postgresql:")){ return new PostgreSQLDialect(); } else if(url.startsWith("jdbc:oracle:")){ return new OracleDialect(); } else if(url.startsWith("jdbc:hsqldb:")){ return new HyperSQLDialect(); } else if(url.startsWith("jdbc:h2:")){ return new H2Dialect(); } else if(url.startsWith("jdbc:derby:")){ return new DerbyDialect(); } else if(url.startsWith("jdbc:sqlite:")){ return new SQLiteDialect(); } else if(url.startsWith("jdbc:sqlserver:") || url.startsWith("jdbc:jtds:sqlserver:")){ return new SQLServerDialect(); } else if(url.startsWith("jdbc:db2:") || url.startsWith("jdbc:db2j:") || url.startsWith("jdbc:db2:ids") || url.startsWith("jdbc:informix-sqli:") || url.startsWith("jdbc:as400:")){ return new DB2Dialect(); } return new StandardDialect(); }
java
public static Dialect getDialect(String url){ if(url.startsWith("jdbc:mysql:")){ return new MySQLDialect(); } else if(url.startsWith("jdbc:postgresql:")){ return new PostgreSQLDialect(); } else if(url.startsWith("jdbc:oracle:")){ return new OracleDialect(); } else if(url.startsWith("jdbc:hsqldb:")){ return new HyperSQLDialect(); } else if(url.startsWith("jdbc:h2:")){ return new H2Dialect(); } else if(url.startsWith("jdbc:derby:")){ return new DerbyDialect(); } else if(url.startsWith("jdbc:sqlite:")){ return new SQLiteDialect(); } else if(url.startsWith("jdbc:sqlserver:") || url.startsWith("jdbc:jtds:sqlserver:")){ return new SQLServerDialect(); } else if(url.startsWith("jdbc:db2:") || url.startsWith("jdbc:db2j:") || url.startsWith("jdbc:db2:ids") || url.startsWith("jdbc:informix-sqli:") || url.startsWith("jdbc:as400:")){ return new DB2Dialect(); } return new StandardDialect(); }
[ "public", "static", "Dialect", "getDialect", "(", "String", "url", ")", "{", "if", "(", "url", ".", "startsWith", "(", "\"jdbc:mysql:\"", ")", ")", "{", "return", "new", "MySQLDialect", "(", ")", ";", "}", "else", "if", "(", "url", ".", "startsWith", "...
Selects the Database Dialect based on the JDBC connection URL. @param url the JDBC Connection URL @return the dialect that maps to a specific JDBC URL.
[ "Selects", "the", "Database", "Dialect", "based", "on", "the", "JDBC", "connection", "URL", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/session/DialectAutoSelector.java#L13-L36
36,613
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/parser/SqlTokenizerImpl.java
SqlTokenizerImpl.parseComment
protected void parseComment() { int commentEndPos = sql.indexOf("*/", position); int commentEndPos2 = sql.indexOf("*#", position); if (0 < commentEndPos2 && commentEndPos2 < commentEndPos) { commentEndPos = commentEndPos2; } if (commentEndPos < 0) { throw new TwoWaySQLException(String.format( "%s is not closed with %s.", sql.substring(position), "*/")); } token = sql.substring(position, commentEndPos); nextTokenType = TokenType.SQL; position = commentEndPos + 2; tokenType = TokenType.COMMENT; }
java
protected void parseComment() { int commentEndPos = sql.indexOf("*/", position); int commentEndPos2 = sql.indexOf("*#", position); if (0 < commentEndPos2 && commentEndPos2 < commentEndPos) { commentEndPos = commentEndPos2; } if (commentEndPos < 0) { throw new TwoWaySQLException(String.format( "%s is not closed with %s.", sql.substring(position), "*/")); } token = sql.substring(position, commentEndPos); nextTokenType = TokenType.SQL; position = commentEndPos + 2; tokenType = TokenType.COMMENT; }
[ "protected", "void", "parseComment", "(", ")", "{", "int", "commentEndPos", "=", "sql", ".", "indexOf", "(", "\"*/\"", ",", "position", ")", ";", "int", "commentEndPos2", "=", "sql", ".", "indexOf", "(", "\"*#\"", ",", "position", ")", ";", "if", "(", ...
Parse the comment.
[ "Parse", "the", "comment", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/parser/SqlTokenizerImpl.java#L184-L198
36,614
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/bean/BeanDescFactory.java
BeanDescFactory.getBeanDesc
@SuppressWarnings("unchecked") public BeanDesc getBeanDesc(Object obj){ if(obj instanceof Map){ return new MapBeanDescImpl((Map<String, Object>) obj); } else { return getBeanDesc(obj.getClass()); } }
java
@SuppressWarnings("unchecked") public BeanDesc getBeanDesc(Object obj){ if(obj instanceof Map){ return new MapBeanDescImpl((Map<String, Object>) obj); } else { return getBeanDesc(obj.getClass()); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "BeanDesc", "getBeanDesc", "(", "Object", "obj", ")", "{", "if", "(", "obj", "instanceof", "Map", ")", "{", "return", "new", "MapBeanDescImpl", "(", "(", "Map", "<", "String", ",", "Object", ">"...
Constructs a bean descriptor out of an Object instance. @param obj the object to create the descriptor from (the object can also be a Map) @return a descriptor
[ "Constructs", "a", "bean", "descriptor", "out", "of", "an", "Object", "instance", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/bean/BeanDescFactory.java#L35-L42
36,615
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/bean/BeanDescFactory.java
BeanDescFactory.getBeanDesc
public BeanDesc getBeanDesc(Class<?> clazz){ if(clazz == Map.class || clazz == HashMap.class || clazz == LinkedHashMap.class){ return new MapBeanDescImpl(); } if(cacheEnabled && cacheMap.containsKey(clazz)){ return cacheMap.get(clazz); } BeanDesc beanDesc = new BeanDescImpl(clazz, propertyExtractor.extractProperties(clazz)); if(cacheEnabled){ cacheMap.put(clazz, beanDesc); } return beanDesc; }
java
public BeanDesc getBeanDesc(Class<?> clazz){ if(clazz == Map.class || clazz == HashMap.class || clazz == LinkedHashMap.class){ return new MapBeanDescImpl(); } if(cacheEnabled && cacheMap.containsKey(clazz)){ return cacheMap.get(clazz); } BeanDesc beanDesc = new BeanDescImpl(clazz, propertyExtractor.extractProperties(clazz)); if(cacheEnabled){ cacheMap.put(clazz, beanDesc); } return beanDesc; }
[ "public", "BeanDesc", "getBeanDesc", "(", "Class", "<", "?", ">", "clazz", ")", "{", "if", "(", "clazz", "==", "Map", ".", "class", "||", "clazz", "==", "HashMap", ".", "class", "||", "clazz", "==", "LinkedHashMap", ".", "class", ")", "{", "return", ...
Constructs a bean descriptor out of a class. @param clazz the class to create the descriptor from. For <code>Map.class</code>, <code>HashMap.class</code> and <code>LinkedHashMap.class</code> no properties can be extracted, so this operations needs to be done later. @return a descriptor
[ "Constructs", "a", "bean", "descriptor", "out", "of", "a", "class", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/bean/BeanDescFactory.java#L51-L67
36,616
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java
SqlParserImpl.parseSql
protected void parseSql() { String sql = tokenizer.getToken(); if (isElseMode()) { sql = StringUtil.replace(sql, "--", ""); } Node node = peek(); if ((node instanceof IfNode || node instanceof ElseNode) && node.getChildSize() == 0) { SqlTokenizer st = new SqlTokenizerImpl(sql); st.skipWhitespace(); String token = st.skipToken(); st.skipWhitespace(); if (sql.startsWith(",")) { if (sql.startsWith(", ")) { node.addChild(new PrefixSqlNode(", ", sql.substring(2))); } else { node.addChild(new PrefixSqlNode(",", sql.substring(1))); } } else if ("AND".equalsIgnoreCase(token) || "OR".equalsIgnoreCase(token)) { node.addChild(new PrefixSqlNode(st.getBefore(), st.getAfter())); } else { node.addChild(new SqlNode(sql)); } } else { node.addChild(new SqlNode(sql)); } }
java
protected void parseSql() { String sql = tokenizer.getToken(); if (isElseMode()) { sql = StringUtil.replace(sql, "--", ""); } Node node = peek(); if ((node instanceof IfNode || node instanceof ElseNode) && node.getChildSize() == 0) { SqlTokenizer st = new SqlTokenizerImpl(sql); st.skipWhitespace(); String token = st.skipToken(); st.skipWhitespace(); if (sql.startsWith(",")) { if (sql.startsWith(", ")) { node.addChild(new PrefixSqlNode(", ", sql.substring(2))); } else { node.addChild(new PrefixSqlNode(",", sql.substring(1))); } } else if ("AND".equalsIgnoreCase(token) || "OR".equalsIgnoreCase(token)) { node.addChild(new PrefixSqlNode(st.getBefore(), st.getAfter())); } else { node.addChild(new SqlNode(sql)); } } else { node.addChild(new SqlNode(sql)); } }
[ "protected", "void", "parseSql", "(", ")", "{", "String", "sql", "=", "tokenizer", ".", "getToken", "(", ")", ";", "if", "(", "isElseMode", "(", ")", ")", "{", "sql", "=", "StringUtil", ".", "replace", "(", "sql", ",", "\"--\"", ",", "\"\"", ")", "...
Parse the SQL.
[ "Parse", "the", "SQL", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java#L79-L107
36,617
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java
SqlParserImpl.parseComment
protected void parseComment() { String comment = tokenizer.getToken(); if (isTargetComment(comment)) { if (isIfComment(comment)) { parseIf(); } else if (isBeginComment(comment)) { parseBegin(); } else if (isEndComment(comment)) { return; } else { parseCommentBindVariable(); } } else if(isHintComment(comment)){ peek().addChild(new SqlNode("/*" + comment + "*/")); } }
java
protected void parseComment() { String comment = tokenizer.getToken(); if (isTargetComment(comment)) { if (isIfComment(comment)) { parseIf(); } else if (isBeginComment(comment)) { parseBegin(); } else if (isEndComment(comment)) { return; } else { parseCommentBindVariable(); } } else if(isHintComment(comment)){ peek().addChild(new SqlNode("/*" + comment + "*/")); } }
[ "protected", "void", "parseComment", "(", ")", "{", "String", "comment", "=", "tokenizer", ".", "getToken", "(", ")", ";", "if", "(", "isTargetComment", "(", "comment", ")", ")", "{", "if", "(", "isIfComment", "(", "comment", ")", ")", "{", "parseIf", ...
Parse an SQL comment.
[ "Parse", "an", "SQL", "comment", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java#L112-L127
36,618
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java
SqlParserImpl.parseIf
protected void parseIf() { String condition = tokenizer.getToken().substring(2).trim(); if (StringUtil.isEmpty(condition)) { throw new TwoWaySQLException("If condition not found."); } IfNode ifNode = new IfNode(condition); peek().addChild(ifNode); push(ifNode); parseEnd(); }
java
protected void parseIf() { String condition = tokenizer.getToken().substring(2).trim(); if (StringUtil.isEmpty(condition)) { throw new TwoWaySQLException("If condition not found."); } IfNode ifNode = new IfNode(condition); peek().addChild(ifNode); push(ifNode); parseEnd(); }
[ "protected", "void", "parseIf", "(", ")", "{", "String", "condition", "=", "tokenizer", ".", "getToken", "(", ")", ".", "substring", "(", "2", ")", ".", "trim", "(", ")", ";", "if", "(", "StringUtil", ".", "isEmpty", "(", "condition", ")", ")", "{", ...
Parse an IF node.
[ "Parse", "an", "IF", "node", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java#L132-L141
36,619
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java
SqlParserImpl.parseBegin
protected void parseBegin() { BeginNode beginNode = new BeginNode(); peek().addChild(beginNode); push(beginNode); parseEnd(); }
java
protected void parseBegin() { BeginNode beginNode = new BeginNode(); peek().addChild(beginNode); push(beginNode); parseEnd(); }
[ "protected", "void", "parseBegin", "(", ")", "{", "BeginNode", "beginNode", "=", "new", "BeginNode", "(", ")", ";", "peek", "(", ")", ".", "addChild", "(", "beginNode", ")", ";", "push", "(", "beginNode", ")", ";", "parseEnd", "(", ")", ";", "}" ]
Parse a BEGIN node.
[ "Parse", "a", "BEGIN", "node", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java#L146-L151
36,620
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java
SqlParserImpl.parseEnd
protected void parseEnd() { while (TokenType.EOF != tokenizer.next()) { if (tokenizer.getTokenType() == TokenType.COMMENT && isEndComment(tokenizer.getToken())) { pop(); return; } parseToken(); } throw new TwoWaySQLException(String.format( "END comment of %s not found.", tokenizer.getSql())); }
java
protected void parseEnd() { while (TokenType.EOF != tokenizer.next()) { if (tokenizer.getTokenType() == TokenType.COMMENT && isEndComment(tokenizer.getToken())) { pop(); return; } parseToken(); } throw new TwoWaySQLException(String.format( "END comment of %s not found.", tokenizer.getSql())); }
[ "protected", "void", "parseEnd", "(", ")", "{", "while", "(", "TokenType", ".", "EOF", "!=", "tokenizer", ".", "next", "(", ")", ")", "{", "if", "(", "tokenizer", ".", "getTokenType", "(", ")", "==", "TokenType", ".", "COMMENT", "&&", "isEndComment", "...
Parse an END node.
[ "Parse", "an", "END", "node", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java#L156-L168
36,621
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java
SqlParserImpl.parseElse
protected void parseElse() { Node parent = peek(); if (!(parent instanceof IfNode)) { return; } IfNode ifNode = (IfNode) pop(); ElseNode elseNode = new ElseNode(); ifNode.setElseNode(elseNode); push(elseNode); tokenizer.skipWhitespace(); }
java
protected void parseElse() { Node parent = peek(); if (!(parent instanceof IfNode)) { return; } IfNode ifNode = (IfNode) pop(); ElseNode elseNode = new ElseNode(); ifNode.setElseNode(elseNode); push(elseNode); tokenizer.skipWhitespace(); }
[ "protected", "void", "parseElse", "(", ")", "{", "Node", "parent", "=", "peek", "(", ")", ";", "if", "(", "!", "(", "parent", "instanceof", "IfNode", ")", ")", "{", "return", ";", "}", "IfNode", "ifNode", "=", "(", "IfNode", ")", "pop", "(", ")", ...
Parse an ELSE node.
[ "Parse", "an", "ELSE", "node", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java#L173-L183
36,622
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java
SqlParserImpl.parseBindVariable
protected void parseBindVariable() { String expr = tokenizer.getToken(); peek().addChild(new BindVariableNode(expr, beanDescFactory)); }
java
protected void parseBindVariable() { String expr = tokenizer.getToken(); peek().addChild(new BindVariableNode(expr, beanDescFactory)); }
[ "protected", "void", "parseBindVariable", "(", ")", "{", "String", "expr", "=", "tokenizer", ".", "getToken", "(", ")", ";", "peek", "(", ")", ".", "addChild", "(", "new", "BindVariableNode", "(", "expr", ",", "beanDescFactory", ")", ")", ";", "}" ]
Parse the bind variable.
[ "Parse", "the", "bind", "variable", "." ]
29a44b7ad267b5a48bc250cd0ef7d74813d46889
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/parser/SqlParserImpl.java#L205-L208
36,623
iipc/webarchive-commons
src/main/java/org/archive/io/WriterPool.java
WriterPool.makeNewWriterIfAppropriate
protected synchronized WriterPoolMember makeNewWriterIfAppropriate() { long now = System.currentTimeMillis(); lastWriterNeededTime = now; if(currentActive < maxActive) { currentActive++; lastWriterRolloverTime = now; return makeWriter(); } return null; }
java
protected synchronized WriterPoolMember makeNewWriterIfAppropriate() { long now = System.currentTimeMillis(); lastWriterNeededTime = now; if(currentActive < maxActive) { currentActive++; lastWriterRolloverTime = now; return makeWriter(); } return null; }
[ "protected", "synchronized", "WriterPoolMember", "makeNewWriterIfAppropriate", "(", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "lastWriterNeededTime", "=", "now", ";", "if", "(", "currentActive", "<", "maxActive", ")", "{", ...
Create a new writer instance, if still below maxActive count. Remember times to help make later decision when writer should be discarded. @return WriterPoolMember or null if already at max
[ "Create", "a", "new", "writer", "instance", "if", "still", "below", "maxActive", "count", ".", "Remember", "times", "to", "help", "make", "later", "decision", "when", "writer", "should", "be", "discarded", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/WriterPool.java#L148-L157
36,624
iipc/webarchive-commons
src/main/java/org/archive/io/WriterPool.java
WriterPool.invalidateFile
public synchronized void invalidateFile(WriterPoolMember f) throws IOException { try { destroyWriter(f); } catch (Exception e) { // Convert exception. throw new IOException(e.getMessage()); } // It'll have been closed. Rename with an '.invalid' suffix so it // gets attention. File file = f.getFile(); file.renameTo(new File(file.getAbsoluteFile() + WriterPoolMember.INVALID_SUFFIX)); }
java
public synchronized void invalidateFile(WriterPoolMember f) throws IOException { try { destroyWriter(f); } catch (Exception e) { // Convert exception. throw new IOException(e.getMessage()); } // It'll have been closed. Rename with an '.invalid' suffix so it // gets attention. File file = f.getFile(); file.renameTo(new File(file.getAbsoluteFile() + WriterPoolMember.INVALID_SUFFIX)); }
[ "public", "synchronized", "void", "invalidateFile", "(", "WriterPoolMember", "f", ")", "throws", "IOException", "{", "try", "{", "destroyWriter", "(", "f", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// Convert exception.", "throw", "new", "IOExc...
Close and discard a writer that experienced a potentially-corrupting error. @param f writer with problem @throws IOException
[ "Close", "and", "discard", "a", "writer", "that", "experienced", "a", "potentially", "-", "corrupting", "error", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/WriterPool.java#L209-L222
36,625
iipc/webarchive-commons
src/main/java/org/archive/io/HeaderedArchiveRecord.java
HeaderedArchiveRecord.skipHttpHeader
public void skipHttpHeader() throws IOException { if (this.contentHeaderStream == null) { return; } // Empty the contentHeaderStream for (int available = this.contentHeaderStream.available(); this.contentHeaderStream != null && (available = this.contentHeaderStream.available()) > 0;) { // We should be in this loop once only we should only do this // buffer allocation once. byte[] buffer = new byte[available]; // The read nulls out httpHeaderStream when done with it so // need check for null in the loop control line. read(buffer, 0, available); } }
java
public void skipHttpHeader() throws IOException { if (this.contentHeaderStream == null) { return; } // Empty the contentHeaderStream for (int available = this.contentHeaderStream.available(); this.contentHeaderStream != null && (available = this.contentHeaderStream.available()) > 0;) { // We should be in this loop once only we should only do this // buffer allocation once. byte[] buffer = new byte[available]; // The read nulls out httpHeaderStream when done with it so // need check for null in the loop control line. read(buffer, 0, available); } }
[ "public", "void", "skipHttpHeader", "(", ")", "throws", "IOException", "{", "if", "(", "this", ".", "contentHeaderStream", "==", "null", ")", "{", "return", ";", "}", "// Empty the contentHeaderStream", "for", "(", "int", "available", "=", "this", ".", "conten...
Skip over the the content headers if present. Subsequent reads will get the body. <p>Calling this method in the midst of reading the header will make for strange results. Otherwise, safe to call at any time though before reading any of the record content is only time that it makes sense. <p>After calling this method, you can call {@link #getContentHeaders()} to get the read http header. @throws IOException
[ "Skip", "over", "the", "the", "content", "headers", "if", "present", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/HeaderedArchiveRecord.java#L92-L107
36,626
iipc/webarchive-commons
src/main/java/org/archive/io/HeaderedArchiveRecord.java
HeaderedArchiveRecord.readContentHeaders
private InputStream readContentHeaders() throws IOException { // If judged a record that doesn't have an http header, return // immediately. if (!hasContentHeaders()) { return null; } byte [] statusBytes = LaxHttpParser.readRawLine(getIn()); int eolCharCount = getEolCharsCount(statusBytes); if (eolCharCount <= 0) { throw new IOException("Failed to read raw lie where one " + " was expected: " + new String(statusBytes)); } String statusLine = EncodingUtil.getString(statusBytes, 0, statusBytes.length - eolCharCount, ARCConstants.DEFAULT_ENCODING); if (statusLine == null) { throw new NullPointerException("Expected status line is null"); } // TODO: Tighten up this test. boolean isHttpResponse = StatusLine.startsWithHTTP(statusLine); boolean isHttpRequest = false; if (!isHttpResponse) { isHttpRequest = statusLine.toUpperCase().startsWith("GET") || !statusLine.toUpperCase().startsWith("POST"); } if (!isHttpResponse && !isHttpRequest) { throw new UnexpectedStartLineIOException("Failed parse of " + "status line: " + statusLine); } this.statusCode = isHttpResponse? (new StatusLine(statusLine)).getStatusCode(): -1; // Save off all bytes read. Keep them as bytes rather than // convert to strings so we don't have to worry about encodings // though this should never be a problem doing http headers since // its all supposed to be ascii. ByteArrayOutputStream baos = new ByteArrayOutputStream(statusBytes.length + 4 * 1024); baos.write(statusBytes); // Now read rest of the header lines looking for the separation // between header and body. for (byte [] lineBytes = null; true;) { lineBytes = LaxHttpParser.readRawLine(getIn()); eolCharCount = getEolCharsCount(lineBytes); if (eolCharCount <= 0) { throw new IOException("Failed reading headers: " + ((lineBytes != null)? new String(lineBytes): null)); } // Save the bytes read. baos.write(lineBytes); if ((lineBytes.length - eolCharCount) <= 0) { // We've finished reading the http header. break; } } byte [] headerBytes = baos.toByteArray(); // Save off where content body, post content headers, starts. this.contentHeadersLength = headerBytes.length; ByteArrayInputStream bais = new ByteArrayInputStream(headerBytes); if (!bais.markSupported()) { throw new IOException("ByteArrayInputStream does not support mark"); } bais.mark(headerBytes.length); // Read the status line. Don't let it into the parseHeaders function. // It doesn't know what to do with it. bais.read(statusBytes, 0, statusBytes.length); this.contentHeaders = LaxHttpParser.parseHeaders(bais, ARCConstants.DEFAULT_ENCODING); bais.reset(); return bais; }
java
private InputStream readContentHeaders() throws IOException { // If judged a record that doesn't have an http header, return // immediately. if (!hasContentHeaders()) { return null; } byte [] statusBytes = LaxHttpParser.readRawLine(getIn()); int eolCharCount = getEolCharsCount(statusBytes); if (eolCharCount <= 0) { throw new IOException("Failed to read raw lie where one " + " was expected: " + new String(statusBytes)); } String statusLine = EncodingUtil.getString(statusBytes, 0, statusBytes.length - eolCharCount, ARCConstants.DEFAULT_ENCODING); if (statusLine == null) { throw new NullPointerException("Expected status line is null"); } // TODO: Tighten up this test. boolean isHttpResponse = StatusLine.startsWithHTTP(statusLine); boolean isHttpRequest = false; if (!isHttpResponse) { isHttpRequest = statusLine.toUpperCase().startsWith("GET") || !statusLine.toUpperCase().startsWith("POST"); } if (!isHttpResponse && !isHttpRequest) { throw new UnexpectedStartLineIOException("Failed parse of " + "status line: " + statusLine); } this.statusCode = isHttpResponse? (new StatusLine(statusLine)).getStatusCode(): -1; // Save off all bytes read. Keep them as bytes rather than // convert to strings so we don't have to worry about encodings // though this should never be a problem doing http headers since // its all supposed to be ascii. ByteArrayOutputStream baos = new ByteArrayOutputStream(statusBytes.length + 4 * 1024); baos.write(statusBytes); // Now read rest of the header lines looking for the separation // between header and body. for (byte [] lineBytes = null; true;) { lineBytes = LaxHttpParser.readRawLine(getIn()); eolCharCount = getEolCharsCount(lineBytes); if (eolCharCount <= 0) { throw new IOException("Failed reading headers: " + ((lineBytes != null)? new String(lineBytes): null)); } // Save the bytes read. baos.write(lineBytes); if ((lineBytes.length - eolCharCount) <= 0) { // We've finished reading the http header. break; } } byte [] headerBytes = baos.toByteArray(); // Save off where content body, post content headers, starts. this.contentHeadersLength = headerBytes.length; ByteArrayInputStream bais = new ByteArrayInputStream(headerBytes); if (!bais.markSupported()) { throw new IOException("ByteArrayInputStream does not support mark"); } bais.mark(headerBytes.length); // Read the status line. Don't let it into the parseHeaders function. // It doesn't know what to do with it. bais.read(statusBytes, 0, statusBytes.length); this.contentHeaders = LaxHttpParser.parseHeaders(bais, ARCConstants.DEFAULT_ENCODING); bais.reset(); return bais; }
[ "private", "InputStream", "readContentHeaders", "(", ")", "throws", "IOException", "{", "// If judged a record that doesn't have an http header, return", "// immediately.", "if", "(", "!", "hasContentHeaders", "(", ")", ")", "{", "return", "null", ";", "}", "byte", "[",...
Read header if present. Technique borrowed from HttpClient HttpParse class. Using http parser code for now. Later move to more generic header parsing code if there proves a need. @return ByteArrayInputStream with the http header in it or null if no http header. @throws IOException
[ "Read", "header", "if", "present", ".", "Technique", "borrowed", "from", "HttpClient", "HttpParse", "class", ".", "Using", "http", "parser", "code", "for", "now", ".", "Later", "move", "to", "more", "generic", "header", "parsing", "code", "if", "there", "pro...
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/HeaderedArchiveRecord.java#L140-L212
36,627
iipc/webarchive-commons
src/main/java/org/archive/util/ProcessUtils.java
ProcessUtils.exec
public static ProcessUtils.ProcessResult exec(String [] args) throws IOException { Process p = Runtime.getRuntime().exec(args); ProcessUtils pu = new ProcessUtils(); // Gobble up any output. StreamGobbler err = pu.new StreamGobbler(p.getErrorStream(), "stderr"); err.setDaemon(true); err.start(); StreamGobbler out = pu.new StreamGobbler(p.getInputStream(), "stdout"); out.setDaemon(true); out.start(); int exitVal; try { exitVal = p.waitFor(); } catch (InterruptedException e) { throw new IOException("Wait on process " + Arrays.toString(args) + " interrupted: " + e.getMessage()); } ProcessUtils.ProcessResult result = pu.new ProcessResult(args, exitVal, out.getSink(), err.getSink()); if (exitVal != 0) { throw new IOException(result.toString()); } else if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info(result.toString()); } return result; }
java
public static ProcessUtils.ProcessResult exec(String [] args) throws IOException { Process p = Runtime.getRuntime().exec(args); ProcessUtils pu = new ProcessUtils(); // Gobble up any output. StreamGobbler err = pu.new StreamGobbler(p.getErrorStream(), "stderr"); err.setDaemon(true); err.start(); StreamGobbler out = pu.new StreamGobbler(p.getInputStream(), "stdout"); out.setDaemon(true); out.start(); int exitVal; try { exitVal = p.waitFor(); } catch (InterruptedException e) { throw new IOException("Wait on process " + Arrays.toString(args) + " interrupted: " + e.getMessage()); } ProcessUtils.ProcessResult result = pu.new ProcessResult(args, exitVal, out.getSink(), err.getSink()); if (exitVal != 0) { throw new IOException(result.toString()); } else if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info(result.toString()); } return result; }
[ "public", "static", "ProcessUtils", ".", "ProcessResult", "exec", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "Process", "p", "=", "Runtime", ".", "getRuntime", "(", ")", ".", "exec", "(", "args", ")", ";", "ProcessUtils", "pu", "...
Runs process. @param args List of process args. @return A ProcessResult data structure. @throws IOException If interrupted, we throw an IOException. If non-zero exit code, we throw an IOException (This may need to change).
[ "Runs", "process", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/ProcessUtils.java#L124-L150
36,628
iipc/webarchive-commons
src/main/java/org/archive/io/RecordingOutputStream.java
RecordingOutputStream.open
public void open(OutputStream wrappedStream) throws IOException { if(isOpen()) { // error; should not be opening/wrapping in an unclosed // stream remains open throw new IOException("ROS already open for " +Thread.currentThread().getName()); } clearForReuse(); this.out = wrappedStream; startTime = System.currentTimeMillis(); }
java
public void open(OutputStream wrappedStream) throws IOException { if(isOpen()) { // error; should not be opening/wrapping in an unclosed // stream remains open throw new IOException("ROS already open for " +Thread.currentThread().getName()); } clearForReuse(); this.out = wrappedStream; startTime = System.currentTimeMillis(); }
[ "public", "void", "open", "(", "OutputStream", "wrappedStream", ")", "throws", "IOException", "{", "if", "(", "isOpen", "(", ")", ")", "{", "// error; should not be opening/wrapping in an unclosed ", "// stream remains open", "throw", "new", "IOException", "(", "\"ROS a...
Wrap the given stream, both recording and passing along any data written to this RecordingOutputStream. @param wrappedStream Stream to wrap. May be null for case where we want to write to a file backed stream only. @throws IOException If failed creation of backing file.
[ "Wrap", "the", "given", "stream", "both", "recording", "and", "passing", "along", "any", "data", "written", "to", "this", "RecordingOutputStream", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/RecordingOutputStream.java#L195-L205
36,629
iipc/webarchive-commons
src/main/java/org/archive/io/RecordingOutputStream.java
RecordingOutputStream.checkLimits
protected void checkLimits() throws RecorderIOException { // too much material before finding end of headers? if (messageBodyBeginMark<0) { // no mark yet if(position>MAX_HEADER_MATERIAL) { throw new RecorderTooMuchHeaderException(); } } // overlong? if(position>maxLength) { throw new RecorderLengthExceededException(); } // taking too long? long duration = System.currentTimeMillis() - startTime; duration = Math.max(duration,1); // !divzero if(duration>timeoutMs) { throw new RecorderTimeoutException(); } // need to throttle reading to hit max configured rate? if(position/duration >= maxRateBytesPerMs) { long desiredDuration = position / maxRateBytesPerMs; try { Thread.sleep(desiredDuration-duration); } catch (InterruptedException e) { logger.log(Level.WARNING, "bandwidth throttling sleep interrupted", e); } } }
java
protected void checkLimits() throws RecorderIOException { // too much material before finding end of headers? if (messageBodyBeginMark<0) { // no mark yet if(position>MAX_HEADER_MATERIAL) { throw new RecorderTooMuchHeaderException(); } } // overlong? if(position>maxLength) { throw new RecorderLengthExceededException(); } // taking too long? long duration = System.currentTimeMillis() - startTime; duration = Math.max(duration,1); // !divzero if(duration>timeoutMs) { throw new RecorderTimeoutException(); } // need to throttle reading to hit max configured rate? if(position/duration >= maxRateBytesPerMs) { long desiredDuration = position / maxRateBytesPerMs; try { Thread.sleep(desiredDuration-duration); } catch (InterruptedException e) { logger.log(Level.WARNING, "bandwidth throttling sleep interrupted", e); } } }
[ "protected", "void", "checkLimits", "(", ")", "throws", "RecorderIOException", "{", "// too much material before finding end of headers? ", "if", "(", "messageBodyBeginMark", "<", "0", ")", "{", "// no mark yet", "if", "(", "position", ">", "MAX_HEADER_MATERIAL", ")", "...
Check any enforced limits.
[ "Check", "any", "enforced", "limits", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/RecordingOutputStream.java#L313-L341
36,630
iipc/webarchive-commons
src/main/java/org/archive/io/RecordingOutputStream.java
RecordingOutputStream.record
private void record(int b) throws IOException { if (this.shouldDigest) { this.digest.update((byte)b); } if (this.position >= this.buffer.length) { this.ensureDiskStream().write(b); } else { this.buffer[(int) this.position] = (byte) b; } this.position++; }
java
private void record(int b) throws IOException { if (this.shouldDigest) { this.digest.update((byte)b); } if (this.position >= this.buffer.length) { this.ensureDiskStream().write(b); } else { this.buffer[(int) this.position] = (byte) b; } this.position++; }
[ "private", "void", "record", "(", "int", "b", ")", "throws", "IOException", "{", "if", "(", "this", ".", "shouldDigest", ")", "{", "this", ".", "digest", ".", "update", "(", "(", "byte", ")", "b", ")", ";", "}", "if", "(", "this", ".", "position", ...
Record the given byte for later recovery @param b Int to record. @exception IOException Failed write to backing file.
[ "Record", "the", "given", "byte", "for", "later", "recovery" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/RecordingOutputStream.java#L350-L360
36,631
iipc/webarchive-commons
src/main/java/org/archive/io/RecordingOutputStream.java
RecordingOutputStream.record
private void record(byte[] b, int off, int len) throws IOException { if(this.shouldDigest) { assert this.digest != null: "Digest is null."; this.digest.update(b, off, len); } tailRecord(b, off, len); }
java
private void record(byte[] b, int off, int len) throws IOException { if(this.shouldDigest) { assert this.digest != null: "Digest is null."; this.digest.update(b, off, len); } tailRecord(b, off, len); }
[ "private", "void", "record", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "this", ".", "shouldDigest", ")", "{", "assert", "this", ".", "digest", "!=", "null", ":", "\"Digest is null.\"...
Record the given byte-array range for recovery later @param b Buffer to record. @param off Offset into buffer at which to start recording. @param len Length of buffer to record. @exception IOException Failed write to backing file.
[ "Record", "the", "given", "byte", "-", "array", "range", "for", "recovery", "later" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/RecordingOutputStream.java#L371-L377
36,632
iipc/webarchive-commons
src/main/java/org/archive/io/RecordingOutputStream.java
RecordingOutputStream.tailRecord
private void tailRecord(byte[] b, int off, int len) throws IOException { if(this.position >= this.buffer.length){ this.ensureDiskStream().write(b, off, len); this.position += len; } else { assert this.buffer != null: "Buffer is null"; int toCopy = (int)Math.min(this.buffer.length - this.position, len); assert b != null: "Passed buffer is null"; System.arraycopy(b, off, this.buffer, (int)this.position, toCopy); this.position += toCopy; // TODO verify these are +1 -1 right if (toCopy < len) { tailRecord(b, off + toCopy, len - toCopy); } } }
java
private void tailRecord(byte[] b, int off, int len) throws IOException { if(this.position >= this.buffer.length){ this.ensureDiskStream().write(b, off, len); this.position += len; } else { assert this.buffer != null: "Buffer is null"; int toCopy = (int)Math.min(this.buffer.length - this.position, len); assert b != null: "Passed buffer is null"; System.arraycopy(b, off, this.buffer, (int)this.position, toCopy); this.position += toCopy; // TODO verify these are +1 -1 right if (toCopy < len) { tailRecord(b, off + toCopy, len - toCopy); } } }
[ "private", "void", "tailRecord", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "this", ".", "position", ">=", "this", ".", "buffer", ".", "length", ")", "{", "this", ".", "ensureDiskSt...
Record without digesting. @param b Buffer to record. @param off Offset into buffer at which to start recording. @param len Length of buffer to record. @exception IOException Failed write to backing file.
[ "Record", "without", "digesting", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/RecordingOutputStream.java#L388-L403
36,633
iipc/webarchive-commons
src/main/java/org/archive/io/RecordingOutputStream.java
RecordingOutputStream.setLimits
public void setLimits(long length, long milliseconds, long rateKBps) { maxLength = (length>0) ? length : Long.MAX_VALUE; timeoutMs = (milliseconds>0) ? milliseconds : Long.MAX_VALUE; maxRateBytesPerMs = (rateKBps>0) ? rateKBps*1024/1000 : Long.MAX_VALUE; }
java
public void setLimits(long length, long milliseconds, long rateKBps) { maxLength = (length>0) ? length : Long.MAX_VALUE; timeoutMs = (milliseconds>0) ? milliseconds : Long.MAX_VALUE; maxRateBytesPerMs = (rateKBps>0) ? rateKBps*1024/1000 : Long.MAX_VALUE; }
[ "public", "void", "setLimits", "(", "long", "length", ",", "long", "milliseconds", ",", "long", "rateKBps", ")", "{", "maxLength", "=", "(", "length", ">", "0", ")", "?", "length", ":", "Long", ".", "MAX_VALUE", ";", "timeoutMs", "=", "(", "milliseconds"...
Set limits on length, time, and rate to enforce. @param length @param milliseconds @param rateKBps
[ "Set", "limits", "on", "length", "time", "and", "rate", "to", "enforce", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/RecordingOutputStream.java#L605-L609
36,634
iipc/webarchive-commons
src/main/java/org/archive/io/RecordingOutputStream.java
RecordingOutputStream.resetLimits
public void resetLimits() { maxLength = Long.MAX_VALUE; timeoutMs = Long.MAX_VALUE; maxRateBytesPerMs = Long.MAX_VALUE; }
java
public void resetLimits() { maxLength = Long.MAX_VALUE; timeoutMs = Long.MAX_VALUE; maxRateBytesPerMs = Long.MAX_VALUE; }
[ "public", "void", "resetLimits", "(", ")", "{", "maxLength", "=", "Long", ".", "MAX_VALUE", ";", "timeoutMs", "=", "Long", ".", "MAX_VALUE", ";", "maxRateBytesPerMs", "=", "Long", ".", "MAX_VALUE", ";", "}" ]
Reset limits to effectively-unlimited defaults
[ "Reset", "limits", "to", "effectively", "-", "unlimited", "defaults" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/RecordingOutputStream.java#L614-L618
36,635
iipc/webarchive-commons
src/main/java/org/archive/util/zip/GZIPMembersInputStream.java
GZIPMembersInputStream.countingStream
protected static InputStream countingStream(InputStream in, int lookback) throws IOException { CountingInputStream cin = new CountingInputStream(in); cin.mark(lookback); return cin; }
java
protected static InputStream countingStream(InputStream in, int lookback) throws IOException { CountingInputStream cin = new CountingInputStream(in); cin.mark(lookback); return cin; }
[ "protected", "static", "InputStream", "countingStream", "(", "InputStream", "in", ",", "int", "lookback", ")", "throws", "IOException", "{", "CountingInputStream", "cin", "=", "new", "CountingInputStream", "(", "in", ")", ";", "cin", ".", "mark", "(", "lookback"...
A CountingInputStream is inserted to read compressed-offsets. @param in stream to wrap @param lookback tolerance of initial mark @return original stream wrapped in CountingInputStream @throws IOException
[ "A", "CountingInputStream", "is", "inserted", "to", "read", "compressed", "-", "offsets", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/zip/GZIPMembersInputStream.java#L91-L95
36,636
iipc/webarchive-commons
src/main/java/org/archive/io/GenericReplayCharSequence.java
GenericReplayCharSequence.charAt
public char charAt(int index) { if (index < 0 || index >= this.length()) { throw new IndexOutOfBoundsException("index=" + index + " - should be between 0 and length()=" + this.length()); } // is it in the buffer if (index < prefixBuffer.limit()) { return prefixBuffer.get(index); } // otherwise we gotta get it from disk via memory map long charFileIndex = (long) index - (long) prefixBuffer.limit(); long charFileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters if (charFileIndex * bytesPerChar < mapByteOffset) { logger.log(Level.WARNING,"left-fault; probably don't want to use CharSequence that far backward"); } if (charFileIndex * bytesPerChar < mapByteOffset || charFileIndex - (mapByteOffset / bytesPerChar) >= mappedBuffer.limit()) { // fault /* * mapByteOffset is bounded by 0 and file size +/- size of the map, * and starts as close to <code>fileIndex - * MAP_TARGET_LEFT_PADDING_BYTES</code> as it can while also not * being smaller than it needs to be. */ mapByteOffset = Math.min(charFileIndex * bytesPerChar - MAP_TARGET_LEFT_PADDING_BYTES, charFileLength * bytesPerChar - MAP_MAX_BYTES); mapByteOffset = Math.max(0, mapByteOffset); updateMemoryMappedBuffer(); } return mappedBuffer.get((int)(charFileIndex-(mapByteOffset/bytesPerChar))); }
java
public char charAt(int index) { if (index < 0 || index >= this.length()) { throw new IndexOutOfBoundsException("index=" + index + " - should be between 0 and length()=" + this.length()); } // is it in the buffer if (index < prefixBuffer.limit()) { return prefixBuffer.get(index); } // otherwise we gotta get it from disk via memory map long charFileIndex = (long) index - (long) prefixBuffer.limit(); long charFileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters if (charFileIndex * bytesPerChar < mapByteOffset) { logger.log(Level.WARNING,"left-fault; probably don't want to use CharSequence that far backward"); } if (charFileIndex * bytesPerChar < mapByteOffset || charFileIndex - (mapByteOffset / bytesPerChar) >= mappedBuffer.limit()) { // fault /* * mapByteOffset is bounded by 0 and file size +/- size of the map, * and starts as close to <code>fileIndex - * MAP_TARGET_LEFT_PADDING_BYTES</code> as it can while also not * being smaller than it needs to be. */ mapByteOffset = Math.min(charFileIndex * bytesPerChar - MAP_TARGET_LEFT_PADDING_BYTES, charFileLength * bytesPerChar - MAP_MAX_BYTES); mapByteOffset = Math.max(0, mapByteOffset); updateMemoryMappedBuffer(); } return mappedBuffer.get((int)(charFileIndex-(mapByteOffset/bytesPerChar))); }
[ "public", "char", "charAt", "(", "int", "index", ")", "{", "if", "(", "index", "<", "0", "||", "index", ">=", "this", ".", "length", "(", ")", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", "\"index=\"", "+", "index", "+", "\" - should be be...
Get character at passed absolute position. @param index Index into content @return Character at offset <code>index</code>.
[ "Get", "character", "at", "passed", "absolute", "position", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/GenericReplayCharSequence.java#L276-L309
36,637
iipc/webarchive-commons
src/main/java/org/archive/url/LaxURLCodec.java
LaxURLCodec.decodeUrlLoose
public static final byte[] decodeUrlLoose(byte[] bytes) { if (bytes == null) { return null; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (int i = 0; i < bytes.length; i++) { int b = bytes[i]; if (b == '+') { buffer.write(' '); continue; } if (b == '%') { if(i+2<bytes.length) { int u = Character.digit((char)bytes[i+1], 16); int l = Character.digit((char)bytes[i+2], 16); if (u > -1 && l > -1) { // good encoding int c = ((u << 4) + l); buffer.write((char)c); i += 2; continue; } // else: bad encoding digits, leave '%' in place } // else: insufficient encoding digits, leave '%' in place } buffer.write(b); } return buffer.toByteArray(); }
java
public static final byte[] decodeUrlLoose(byte[] bytes) { if (bytes == null) { return null; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (int i = 0; i < bytes.length; i++) { int b = bytes[i]; if (b == '+') { buffer.write(' '); continue; } if (b == '%') { if(i+2<bytes.length) { int u = Character.digit((char)bytes[i+1], 16); int l = Character.digit((char)bytes[i+2], 16); if (u > -1 && l > -1) { // good encoding int c = ((u << 4) + l); buffer.write((char)c); i += 2; continue; } // else: bad encoding digits, leave '%' in place } // else: insufficient encoding digits, leave '%' in place } buffer.write(b); } return buffer.toByteArray(); }
[ "public", "static", "final", "byte", "[", "]", "decodeUrlLoose", "(", "byte", "[", "]", "bytes", ")", "{", "if", "(", "bytes", "==", "null", ")", "{", "return", "null", ";", "}", "ByteArrayOutputStream", "buffer", "=", "new", "ByteArrayOutputStream", "(", ...
Decodes an array of URL safe 7-bit characters into an array of original bytes. Escaped characters are converted back to their original representation. Differs from URLCodec.decodeUrl() in that it throws no exceptions; bad or incomplete escape sequences are ignored and passed into result undecoded. This matches the behavior of browsers, which will use inconsistently-encoded URIs in HTTP request-lines. @param bytes array of URL safe characters @return array of original bytes
[ "Decodes", "an", "array", "of", "URL", "safe", "7", "-", "bit", "characters", "into", "an", "array", "of", "original", "bytes", ".", "Escaped", "characters", "are", "converted", "back", "to", "their", "original", "representation", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/url/LaxURLCodec.java#L54-L82
36,638
iipc/webarchive-commons
src/main/java/org/archive/url/LaxURLCodec.java
LaxURLCodec.encode
public String encode(BitSet safe, String pString, String cs) throws UnsupportedEncodingException { if (pString == null) { return null; } return new String(encodeUrl(safe,pString.getBytes(cs)), Charsets.US_ASCII); }
java
public String encode(BitSet safe, String pString, String cs) throws UnsupportedEncodingException { if (pString == null) { return null; } return new String(encodeUrl(safe,pString.getBytes(cs)), Charsets.US_ASCII); }
[ "public", "String", "encode", "(", "BitSet", "safe", ",", "String", "pString", ",", "String", "cs", ")", "throws", "UnsupportedEncodingException", "{", "if", "(", "pString", "==", "null", ")", "{", "return", "null", ";", "}", "return", "new", "String", "("...
Encodes a string into its URL safe form using the specified string charset. Unsafe characters are escaped. This method is analogous to superclass encode() methods, additionally offering the ability to specify a different 'safe' character set (such as EXPANDED_URI_SAFE). @param safe BitSet of characters that don't need to be encoded @param pString String to encode @param cs Name of character set to use @return Encoded version of <code>pString</code>. @throws UnsupportedEncodingException
[ "Encodes", "a", "string", "into", "its", "URL", "safe", "form", "using", "the", "specified", "string", "charset", ".", "Unsafe", "characters", "are", "escaped", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/url/LaxURLCodec.java#L153-L159
36,639
iipc/webarchive-commons
src/main/java/org/archive/util/SurtPrefixSet.java
SurtPrefixSet.importFrom
public void importFrom(Reader r) { BufferedReader reader = new BufferedReader(r); String s; Iterator<String> iter = new RegexLineIterator( new LineReadingIterator(reader), RegexLineIterator.COMMENT_LINE, RegexLineIterator.NONWHITESPACE_ENTRY_TRAILING_COMMENT, RegexLineIterator.ENTRY); while (iter.hasNext()) { s = (String) iter.next(); add(s.toLowerCase()); } }
java
public void importFrom(Reader r) { BufferedReader reader = new BufferedReader(r); String s; Iterator<String> iter = new RegexLineIterator( new LineReadingIterator(reader), RegexLineIterator.COMMENT_LINE, RegexLineIterator.NONWHITESPACE_ENTRY_TRAILING_COMMENT, RegexLineIterator.ENTRY); while (iter.hasNext()) { s = (String) iter.next(); add(s.toLowerCase()); } }
[ "public", "void", "importFrom", "(", "Reader", "r", ")", "{", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "r", ")", ";", "String", "s", ";", "Iterator", "<", "String", ">", "iter", "=", "new", "RegexLineIterator", "(", "new", "LineReadin...
Read a set of SURT prefixes from a reader source; keep sorted and with redundant entries removed. @param r reader over file of SURT_format strings @throws IOException
[ "Read", "a", "set", "of", "SURT", "prefixes", "from", "a", "reader", "source", ";", "keep", "sorted", "and", "with", "redundant", "entries", "removed", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/SurtPrefixSet.java#L61-L76
36,640
iipc/webarchive-commons
src/main/java/org/archive/util/SurtPrefixSet.java
SurtPrefixSet.importFromMixed
public void importFromMixed(Reader r, boolean deduceFromSeeds) { BufferedReader reader = new BufferedReader(r); String s; Iterator<String> iter = new RegexLineIterator( new LineReadingIterator(reader), RegexLineIterator.COMMENT_LINE, RegexLineIterator.NONWHITESPACE_ENTRY_TRAILING_COMMENT, RegexLineIterator.ENTRY); while (iter.hasNext()) { s = (String) iter.next(); if(s.startsWith(SURT_PREFIX_DIRECTIVE)) { considerAsAddDirective(s.substring(SURT_PREFIX_DIRECTIVE.length())); continue; } else { if(deduceFromSeeds) { // also deducing 'implied' SURT prefixes // from normal URIs/hostname seeds addFromPlain(s); } } } }
java
public void importFromMixed(Reader r, boolean deduceFromSeeds) { BufferedReader reader = new BufferedReader(r); String s; Iterator<String> iter = new RegexLineIterator( new LineReadingIterator(reader), RegexLineIterator.COMMENT_LINE, RegexLineIterator.NONWHITESPACE_ENTRY_TRAILING_COMMENT, RegexLineIterator.ENTRY); while (iter.hasNext()) { s = (String) iter.next(); if(s.startsWith(SURT_PREFIX_DIRECTIVE)) { considerAsAddDirective(s.substring(SURT_PREFIX_DIRECTIVE.length())); continue; } else { if(deduceFromSeeds) { // also deducing 'implied' SURT prefixes // from normal URIs/hostname seeds addFromPlain(s); } } } }
[ "public", "void", "importFromMixed", "(", "Reader", "r", ",", "boolean", "deduceFromSeeds", ")", "{", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "r", ")", ";", "String", "s", ";", "Iterator", "<", "String", ">", "iter", "=", "new", "Reg...
Import SURT prefixes from a reader with mixed URI and SURT prefix format. @param r the reader to import the prefixes from @param deduceFromSeeds true to also import SURT prefixes implied from normal URIs/hostname seeds
[ "Import", "SURT", "prefixes", "from", "a", "reader", "with", "mixed", "URI", "and", "SURT", "prefix", "format", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/SurtPrefixSet.java#L107-L131
36,641
iipc/webarchive-commons
src/main/java/org/archive/util/SURT.java
SURT.fromURI
public static String fromURI(String s, boolean preserveCase) { Matcher m = TextUtils.getMatcher(URI_SPLITTER,s); if(!m.matches()) { // not an authority-based URI scheme; return unchanged TextUtils.recycleMatcher(m); return s; } // preallocate enough space for SURT form, which includes // 3 extra characters ('(', ')', and one more ',' than '.'s // in original) StringBuffer builder = new StringBuffer(s.length()+3); append(builder,s,m.start(1),m.end(1)); // scheme:// builder.append(BEGIN_TRANSFORMED_AUTHORITY); // '(' if(m.start(4)>-1) { // dotted-quad ip match: don't reverse append(builder,s,m.start(4),m.end(4)); } else { // other hostname match: do reverse int hostSegEnd = m.end(5); int hostStart = m.start(5); for(int i = m.end(5)-1; i>=hostStart; i--) { if(s.charAt(i-1)!=DOT && i > hostStart) { continue; } append(builder,s,i,hostSegEnd); // rev host segment builder.append(TRANSFORMED_HOST_DELIM); // ',' hostSegEnd = i-1; } } append(builder,s,m.start(6),m.end(6)); // :port append(builder,s,m.start(3),m.end(3)); // at append(builder,s,m.start(2),m.end(2)); // userinfo builder.append(END_TRANSFORMED_AUTHORITY); // ')' append(builder,s,m.start(7),m.end(7)); // path if (!preserveCase) { for(int i = 0; i < builder.length(); i++) { builder.setCharAt(i,Character.toLowerCase(builder.charAt((i)))); } } TextUtils.recycleMatcher(m); return builder.toString(); }
java
public static String fromURI(String s, boolean preserveCase) { Matcher m = TextUtils.getMatcher(URI_SPLITTER,s); if(!m.matches()) { // not an authority-based URI scheme; return unchanged TextUtils.recycleMatcher(m); return s; } // preallocate enough space for SURT form, which includes // 3 extra characters ('(', ')', and one more ',' than '.'s // in original) StringBuffer builder = new StringBuffer(s.length()+3); append(builder,s,m.start(1),m.end(1)); // scheme:// builder.append(BEGIN_TRANSFORMED_AUTHORITY); // '(' if(m.start(4)>-1) { // dotted-quad ip match: don't reverse append(builder,s,m.start(4),m.end(4)); } else { // other hostname match: do reverse int hostSegEnd = m.end(5); int hostStart = m.start(5); for(int i = m.end(5)-1; i>=hostStart; i--) { if(s.charAt(i-1)!=DOT && i > hostStart) { continue; } append(builder,s,i,hostSegEnd); // rev host segment builder.append(TRANSFORMED_HOST_DELIM); // ',' hostSegEnd = i-1; } } append(builder,s,m.start(6),m.end(6)); // :port append(builder,s,m.start(3),m.end(3)); // at append(builder,s,m.start(2),m.end(2)); // userinfo builder.append(END_TRANSFORMED_AUTHORITY); // ')' append(builder,s,m.start(7),m.end(7)); // path if (!preserveCase) { for(int i = 0; i < builder.length(); i++) { builder.setCharAt(i,Character.toLowerCase(builder.charAt((i)))); } } TextUtils.recycleMatcher(m); return builder.toString(); }
[ "public", "static", "String", "fromURI", "(", "String", "s", ",", "boolean", "preserveCase", ")", "{", "Matcher", "m", "=", "TextUtils", ".", "getMatcher", "(", "URI_SPLITTER", ",", "s", ")", ";", "if", "(", "!", "m", ".", "matches", "(", ")", ")", "...
Utility method for creating the SURT form of the URI in the given String. If it appears a bit convoluted in its approach, note that it was optimized to minimize object-creation after allocation-sites profiling indicated this method was a top source of garbage in long-running crawls. Assumes that the String URI has already been cleaned/fixed (eg by UURI fixup) in ways that put it in its crawlable form for evaluation. @param s String URI to be converted to SURT form @param preserveCase whether original case should be preserved @return SURT form
[ "Utility", "method", "for", "creating", "the", "SURT", "form", "of", "the", "URI", "in", "the", "given", "String", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/SURT.java#L121-L164
36,642
iipc/webarchive-commons
src/main/java/org/archive/net/rsync/Handler.java
Handler.main
public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: java java " + "-Djava.protocol.handler.pkgs=org.archive.net " + "org.archive.net.rsync.Handler RSYNC_URL"); System.exit(1); } URL u = new URL(args[0]); URLConnection connect = u.openConnection(); // Write download to stdout. final int bufferlength = 4096; byte [] buffer = new byte [bufferlength]; InputStream is = connect.getInputStream(); try { for (int count = is.read(buffer, 0, bufferlength); (count = is.read(buffer, 0, bufferlength)) != -1;) { System.out.write(buffer, 0, count); } System.out.flush(); } finally { is.close(); } }
java
public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: java java " + "-Djava.protocol.handler.pkgs=org.archive.net " + "org.archive.net.rsync.Handler RSYNC_URL"); System.exit(1); } URL u = new URL(args[0]); URLConnection connect = u.openConnection(); // Write download to stdout. final int bufferlength = 4096; byte [] buffer = new byte [bufferlength]; InputStream is = connect.getInputStream(); try { for (int count = is.read(buffer, 0, bufferlength); (count = is.read(buffer, 0, bufferlength)) != -1;) { System.out.write(buffer, 0, count); } System.out.flush(); } finally { is.close(); } }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "if", "(", "args", ".", "length", "!=", "1", ")", "{", "System", ".", "out", ".", "println", "(", "\"Usage: java java \"", "+", "\"-Djava.protocol.handl...
Main dumps rsync file to STDOUT. @param args @throws IOException
[ "Main", "dumps", "rsync", "file", "to", "STDOUT", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/net/rsync/Handler.java#L47-L70
36,643
iipc/webarchive-commons
src/main/java/org/archive/io/ArraySeekInputStream.java
ArraySeekInputStream.position
public void position(long p) throws IOException { if ((p < 0) || (p > array.length)) { throw new IOException("Invalid position: " + p); } offset = (int)p; }
java
public void position(long p) throws IOException { if ((p < 0) || (p > array.length)) { throw new IOException("Invalid position: " + p); } offset = (int)p; }
[ "public", "void", "position", "(", "long", "p", ")", "throws", "IOException", "{", "if", "(", "(", "p", "<", "0", ")", "||", "(", "p", ">", "array", ".", "length", ")", ")", "{", "throw", "new", "IOException", "(", "\"Invalid position: \"", "+", "p",...
Repositions the stream. @param p the new position for the stream @throws IOException if the given position is out of bounds
[ "Repositions", "the", "stream", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/ArraySeekInputStream.java#L99-L104
36,644
iipc/webarchive-commons
src/main/java/org/archive/format/cdx/FieldSplitFormat.java
FieldSplitFormat.getFieldIndex
public int getFieldIndex(String name) { Integer val = this.nameToIndex.get(name); if (val == null) { return -1; } return val; }
java
public int getFieldIndex(String name) { Integer val = this.nameToIndex.get(name); if (val == null) { return -1; } return val; }
[ "public", "int", "getFieldIndex", "(", "String", "name", ")", "{", "Integer", "val", "=", "this", ".", "nameToIndex", ".", "get", "(", "name", ")", ";", "if", "(", "val", "==", "null", ")", "{", "return", "-", "1", ";", "}", "return", "val", ";", ...
Return field index for given name @param name @return
[ "Return", "field", "index", "for", "given", "name" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/format/cdx/FieldSplitFormat.java#L82-L88
36,645
iipc/webarchive-commons
src/main/java/org/archive/util/binsearch/ByteBufferInputStream.java
ByteBufferInputStream.map
public static ByteBufferInputStream map( final FileChannel fileChannel, final MapMode mapMode ) throws IOException { final long size = fileChannel.size(); final int chunks = (int)( ( size + ( CHUNK_SIZE - 1 ) ) / CHUNK_SIZE ); final ByteBuffer[] byteBuffer = new ByteBuffer[ chunks ]; for( int i = 0; i < chunks; i++ ) byteBuffer[ i ] = fileChannel.map( mapMode, i * CHUNK_SIZE, Math.min( CHUNK_SIZE, size - i * CHUNK_SIZE ) ); byteBuffer[ 0 ].position( 0 ); final boolean[] readyToUse = new boolean[ chunks ]; //BooleanArrays.fill( readyToUse, true ); for (int i = 0; i < readyToUse.length; i++) { readyToUse[i] = true; } return new ByteBufferInputStream( byteBuffer, size, 0, readyToUse ); }
java
public static ByteBufferInputStream map( final FileChannel fileChannel, final MapMode mapMode ) throws IOException { final long size = fileChannel.size(); final int chunks = (int)( ( size + ( CHUNK_SIZE - 1 ) ) / CHUNK_SIZE ); final ByteBuffer[] byteBuffer = new ByteBuffer[ chunks ]; for( int i = 0; i < chunks; i++ ) byteBuffer[ i ] = fileChannel.map( mapMode, i * CHUNK_SIZE, Math.min( CHUNK_SIZE, size - i * CHUNK_SIZE ) ); byteBuffer[ 0 ].position( 0 ); final boolean[] readyToUse = new boolean[ chunks ]; //BooleanArrays.fill( readyToUse, true ); for (int i = 0; i < readyToUse.length; i++) { readyToUse[i] = true; } return new ByteBufferInputStream( byteBuffer, size, 0, readyToUse ); }
[ "public", "static", "ByteBufferInputStream", "map", "(", "final", "FileChannel", "fileChannel", ",", "final", "MapMode", "mapMode", ")", "throws", "IOException", "{", "final", "long", "size", "=", "fileChannel", ".", "size", "(", ")", ";", "final", "int", "chu...
Creates a new byte-buffer input stream by mapping a given file channel. @param fileChannel the file channel that will be mapped. @param mapMode this must be {@link MapMode#READ_ONLY}. @return a new byte-buffer input stream over the contents of <code>fileChannel</code>.
[ "Creates", "a", "new", "byte", "-", "buffer", "input", "stream", "by", "mapping", "a", "given", "file", "channel", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/binsearch/ByteBufferInputStream.java#L123-L135
36,646
iipc/webarchive-commons
src/main/java/org/archive/util/DateUtils.java
DateUtils.formatMillisecondsToConventional
public static String formatMillisecondsToConventional(long duration, int unitCount) { if(unitCount <=0) { unitCount = 5; } if(duration==0) { return "0ms"; } StringBuffer sb = new StringBuffer(); if(duration<0) { sb.append("-"); } long absTime = Math.abs(duration); long[] thresholds = {DAY_IN_MS, HOUR_IN_MS, 60000, 1000, 1}; String[] units = {"d","h","m","s","ms"}; for(int i = 0; i < thresholds.length; i++) { if(absTime >= thresholds[i]) { sb.append(absTime / thresholds[i] + units[i]); absTime = absTime % thresholds[i]; unitCount--; } if(unitCount==0) { break; } } return sb.toString(); }
java
public static String formatMillisecondsToConventional(long duration, int unitCount) { if(unitCount <=0) { unitCount = 5; } if(duration==0) { return "0ms"; } StringBuffer sb = new StringBuffer(); if(duration<0) { sb.append("-"); } long absTime = Math.abs(duration); long[] thresholds = {DAY_IN_MS, HOUR_IN_MS, 60000, 1000, 1}; String[] units = {"d","h","m","s","ms"}; for(int i = 0; i < thresholds.length; i++) { if(absTime >= thresholds[i]) { sb.append(absTime / thresholds[i] + units[i]); absTime = absTime % thresholds[i]; unitCount--; } if(unitCount==0) { break; } } return sb.toString(); }
[ "public", "static", "String", "formatMillisecondsToConventional", "(", "long", "duration", ",", "int", "unitCount", ")", "{", "if", "(", "unitCount", "<=", "0", ")", "{", "unitCount", "=", "5", ";", "}", "if", "(", "duration", "==", "0", ")", "{", "retur...
Convert milliseconds value to a human-readable duration of mixed units, using units no larger than days. For example, "5d12h13m12s113ms" or "19h51m". @param duration @param unitCount how many significant units to show, at most for example, a value of 2 would show days+hours or hours+seconds but not hours+second+milliseconds @return Human readable string version of passed <code>time</code>
[ "Convert", "milliseconds", "value", "to", "a", "human", "-", "readable", "duration", "of", "mixed", "units", "using", "units", "no", "larger", "than", "days", ".", "For", "example", "5d12h13m12s113ms", "or", "19h51m", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/DateUtils.java#L610-L636
36,647
iipc/webarchive-commons
src/main/java/org/archive/util/DateUtils.java
DateUtils.getUnique14DigitDate
public synchronized static String getUnique14DigitDate(){ long effectiveNow = System.currentTimeMillis(); effectiveNow = Math.max(effectiveNow, LAST_UNIQUE_NOW14+1); String candidate = get14DigitDate(effectiveNow); while(candidate.equals(LAST_TIMESTAMP14)) { effectiveNow += 1000; candidate = get14DigitDate(effectiveNow); } LAST_UNIQUE_NOW14 = effectiveNow; LAST_TIMESTAMP14 = candidate; return candidate; }
java
public synchronized static String getUnique14DigitDate(){ long effectiveNow = System.currentTimeMillis(); effectiveNow = Math.max(effectiveNow, LAST_UNIQUE_NOW14+1); String candidate = get14DigitDate(effectiveNow); while(candidate.equals(LAST_TIMESTAMP14)) { effectiveNow += 1000; candidate = get14DigitDate(effectiveNow); } LAST_UNIQUE_NOW14 = effectiveNow; LAST_TIMESTAMP14 = candidate; return candidate; }
[ "public", "synchronized", "static", "String", "getUnique14DigitDate", "(", ")", "{", "long", "effectiveNow", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "effectiveNow", "=", "Math", ".", "max", "(", "effectiveNow", ",", "LAST_UNIQUE_NOW14", "+", "1",...
Utility function for creating UNIQUE-from-this-class arc-style date stamps in the format yyyMMddHHmmss. Rather than giving a duplicate datestamp on a subsequent call, will increment the seconds until a unique value is returned. Date stamps are in the UTC time zone @return the date stamp
[ "Utility", "function", "for", "creating", "UNIQUE", "-", "from", "-", "this", "-", "class", "arc", "-", "style", "date", "stamps", "in", "the", "format", "yyyMMddHHmmss", ".", "Rather", "than", "giving", "a", "duplicate", "datestamp", "on", "a", "subsequent"...
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/DateUtils.java#L650-L661
36,648
iipc/webarchive-commons
src/main/java/org/archive/util/iterator/LineReadingIterator.java
LineReadingIterator.lookahead
protected boolean lookahead() { try { next = this.reader.readLine(); if(next == null) { // TODO: make this close-on-exhaust optional? reader.close(); } return (next!=null); } catch (IOException e) { logger.warning(e.toString()); return false; } }
java
protected boolean lookahead() { try { next = this.reader.readLine(); if(next == null) { // TODO: make this close-on-exhaust optional? reader.close(); } return (next!=null); } catch (IOException e) { logger.warning(e.toString()); return false; } }
[ "protected", "boolean", "lookahead", "(", ")", "{", "try", "{", "next", "=", "this", ".", "reader", ".", "readLine", "(", ")", ";", "if", "(", "next", "==", "null", ")", "{", "// TODO: make this close-on-exhaust optional?", "reader", ".", "close", "(", ")"...
Loads next line into lookahead spot @return whether any item was loaded into next field
[ "Loads", "next", "line", "into", "lookahead", "spot" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/iterator/LineReadingIterator.java#L46-L58
36,649
iipc/webarchive-commons
src/main/java/org/archive/format/cdx/CDXFile.java
CDXFile.decodeGZToTemp
public static File decodeGZToTemp(String uriGZ) throws IOException { final int BUFFER_SIZE = 8192; Stream stream = null; try { stream = GeneralURIStreamFactory.createStream(uriGZ); InputStream input = new StreamWrappedInputStream(stream); input = new OpenJDK7GZIPInputStream(input); File uncompressedCdx = File.createTempFile(uriGZ, ".cdx"); FileOutputStream out = new FileOutputStream(uncompressedCdx, false); byte buff[] = new byte[BUFFER_SIZE]; int numRead = 0; while ((numRead = input.read(buff)) > 0) { out.write(buff, 0, numRead); } out.flush(); out.close(); return uncompressedCdx; } finally { if (stream != null) { stream.close(); } } }
java
public static File decodeGZToTemp(String uriGZ) throws IOException { final int BUFFER_SIZE = 8192; Stream stream = null; try { stream = GeneralURIStreamFactory.createStream(uriGZ); InputStream input = new StreamWrappedInputStream(stream); input = new OpenJDK7GZIPInputStream(input); File uncompressedCdx = File.createTempFile(uriGZ, ".cdx"); FileOutputStream out = new FileOutputStream(uncompressedCdx, false); byte buff[] = new byte[BUFFER_SIZE]; int numRead = 0; while ((numRead = input.read(buff)) > 0) { out.write(buff, 0, numRead); } out.flush(); out.close(); return uncompressedCdx; } finally { if (stream != null) { stream.close(); } } }
[ "public", "static", "File", "decodeGZToTemp", "(", "String", "uriGZ", ")", "throws", "IOException", "{", "final", "int", "BUFFER_SIZE", "=", "8192", ";", "Stream", "stream", "=", "null", ";", "try", "{", "stream", "=", "GeneralURIStreamFactory", ".", "createSt...
Decode gzipped cdx to a temporary file
[ "Decode", "gzipped", "cdx", "to", "a", "temporary", "file" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/format/cdx/CDXFile.java#L53-L83
36,650
iipc/webarchive-commons
src/main/java/org/archive/format/cdx/FieldSplitLine.java
FieldSplitLine.getField
public String getField(String name, String defaultVal) { int index = getFieldIndex(name); return (isInRange(index) ? this.fields.get(index) : defaultVal); }
java
public String getField(String name, String defaultVal) { int index = getFieldIndex(name); return (isInRange(index) ? this.fields.get(index) : defaultVal); }
[ "public", "String", "getField", "(", "String", "name", ",", "String", "defaultVal", ")", "{", "int", "index", "=", "getFieldIndex", "(", "name", ")", ";", "return", "(", "isInRange", "(", "index", ")", "?", "this", ".", "fields", ".", "get", "(", "inde...
Return field for given name, or defaultVal if not found @param name @return
[ "Return", "field", "for", "given", "name", "or", "defaultVal", "if", "not", "found" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/format/cdx/FieldSplitLine.java#L94-L97
36,651
iipc/webarchive-commons
src/main/java/org/archive/util/FileUtils.java
FileUtils.copyFile
public static boolean copyFile(final File src, final File dest) throws FileNotFoundException, IOException { return copyFile(src, dest, -1, true); }
java
public static boolean copyFile(final File src, final File dest) throws FileNotFoundException, IOException { return copyFile(src, dest, -1, true); }
[ "public", "static", "boolean", "copyFile", "(", "final", "File", "src", ",", "final", "File", "dest", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "return", "copyFile", "(", "src", ",", "dest", ",", "-", "1", ",", "true", ")", ";", "}...
Copy the src file to the destination. Deletes any preexisting file at destination. @param src @param dest @return True if the extent was greater than actual bytes copied. @throws FileNotFoundException @throws IOException
[ "Copy", "the", "src", "file", "to", "the", "destination", ".", "Deletes", "any", "preexisting", "file", "at", "destination", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/FileUtils.java#L71-L74
36,652
iipc/webarchive-commons
src/main/java/org/archive/util/FileUtils.java
FileUtils.copyFile
public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists()); } if (dest.exists()) { if (overwrite) { dest.delete(); LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); } else { // Already in place and we're not to overwrite. Return. return result; } } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { // Get channels fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); if (extent < 0) { extent = fcin.size(); } // Do the file copy long trans = fcin.transferTo(0, extent, fcout); if (trans < extent) { result = false; } result = true; } catch (IOException e) { // Add more info to the exception. Preserve old stacktrace. // We get 'Invalid argument' on some file copies. See // http://intellij.net/forums/thread.jsp?forum=13&thread=63027&message=853123 // for related issue. String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage(); if ((e instanceof ClosedByInterruptException) || ((e.getMessage()!=null) &&e.getMessage().equals("Invalid argument"))) { LOGGER.severe("Failed copy, trying workaround: " + message); workaroundCopyFile(src, dest); } else { IOException newE = new IOException(message); newE.initCause(e); throw newE; } } finally { // finish up if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } return result; }
java
public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists()); } if (dest.exists()) { if (overwrite) { dest.delete(); LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); } else { // Already in place and we're not to overwrite. Return. return result; } } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { // Get channels fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); if (extent < 0) { extent = fcin.size(); } // Do the file copy long trans = fcin.transferTo(0, extent, fcout); if (trans < extent) { result = false; } result = true; } catch (IOException e) { // Add more info to the exception. Preserve old stacktrace. // We get 'Invalid argument' on some file copies. See // http://intellij.net/forums/thread.jsp?forum=13&thread=63027&message=853123 // for related issue. String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage(); if ((e instanceof ClosedByInterruptException) || ((e.getMessage()!=null) &&e.getMessage().equals("Invalid argument"))) { LOGGER.severe("Failed copy, trying workaround: " + message); workaroundCopyFile(src, dest); } else { IOException newE = new IOException(message); newE.initCause(e); throw newE; } } finally { // finish up if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } return result; }
[ "public", "static", "boolean", "copyFile", "(", "final", "File", "src", ",", "final", "File", "dest", ",", "long", "extent", ",", "final", "boolean", "overwrite", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "boolean", "result", "=", "false...
Copy up to extent bytes of the source file to the destination @param src @param dest @param extent Maximum number of bytes to copy @param overwrite If target file already exits, and this parameter is true, overwrite target file (We do this by first deleting the target file before we begin the copy). @return True if the extent was greater than actual bytes copied. @throws FileNotFoundException @throws IOException
[ "Copy", "up", "to", "extent", "bytes", "of", "the", "source", "file", "to", "the", "destination" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/FileUtils.java#L106-L177
36,653
iipc/webarchive-commons
src/main/java/org/archive/util/FileUtils.java
FileUtils.getFilesWithPrefix
public static File [] getFilesWithPrefix(File dir, final String prefix) { FileFilter prefixFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().toLowerCase(). startsWith(prefix.toLowerCase()); } }; return dir.listFiles(prefixFilter); }
java
public static File [] getFilesWithPrefix(File dir, final String prefix) { FileFilter prefixFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().toLowerCase(). startsWith(prefix.toLowerCase()); } }; return dir.listFiles(prefixFilter); }
[ "public", "static", "File", "[", "]", "getFilesWithPrefix", "(", "File", "dir", ",", "final", "String", "prefix", ")", "{", "FileFilter", "prefixFilter", "=", "new", "FileFilter", "(", ")", "{", "public", "boolean", "accept", "(", "File", "pathname", ")", ...
Get a list of all files in directory that have passed prefix. @param dir Dir to look in. @param prefix Basename of files to look for. Compare is case insensitive. @return List of files in dir that start w/ passed basename.
[ "Get", "a", "list", "of", "all", "files", "in", "directory", "that", "have", "passed", "prefix", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/FileUtils.java#L218-L227
36,654
iipc/webarchive-commons
src/main/java/org/archive/util/FileUtils.java
FileUtils.assertReadable
public static File assertReadable(final File f) throws FileNotFoundException { if (!f.exists()) { throw new FileNotFoundException(f.getAbsolutePath() + " does not exist."); } if (!f.canRead()) { throw new FileNotFoundException(f.getAbsolutePath() + " is not readable."); } return f; }
java
public static File assertReadable(final File f) throws FileNotFoundException { if (!f.exists()) { throw new FileNotFoundException(f.getAbsolutePath() + " does not exist."); } if (!f.canRead()) { throw new FileNotFoundException(f.getAbsolutePath() + " is not readable."); } return f; }
[ "public", "static", "File", "assertReadable", "(", "final", "File", "f", ")", "throws", "FileNotFoundException", "{", "if", "(", "!", "f", ".", "exists", "(", ")", ")", "{", "throw", "new", "FileNotFoundException", "(", "f", ".", "getAbsolutePath", "(", ")...
Test file exists and is readable. @param f File to test. @exception FileNotFoundException If file does not exist or is not unreadable.
[ "Test", "file", "exists", "and", "is", "readable", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/FileUtils.java#L261-L273
36,655
iipc/webarchive-commons
src/main/java/org/archive/util/FileUtils.java
FileUtils.loadProperties
public static Properties loadProperties(File file) throws IOException { FileInputStream finp = new FileInputStream(file); try { Properties p = new Properties(); p.load(finp); return p; } finally { ArchiveUtils.closeQuietly(finp); } }
java
public static Properties loadProperties(File file) throws IOException { FileInputStream finp = new FileInputStream(file); try { Properties p = new Properties(); p.load(finp); return p; } finally { ArchiveUtils.closeQuietly(finp); } }
[ "public", "static", "Properties", "loadProperties", "(", "File", "file", ")", "throws", "IOException", "{", "FileInputStream", "finp", "=", "new", "FileInputStream", "(", "file", ")", ";", "try", "{", "Properties", "p", "=", "new", "Properties", "(", ")", ";...
Load Properties instance from a File @param file @return Properties @throws IOException
[ "Load", "Properties", "instance", "from", "a", "File" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/FileUtils.java#L335-L344
36,656
iipc/webarchive-commons
src/main/java/org/archive/util/FileUtils.java
FileUtils.storeProperties
public static void storeProperties(Properties p, File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { p.store(fos,""); } finally { ArchiveUtils.closeQuietly(fos); } }
java
public static void storeProperties(Properties p, File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { p.store(fos,""); } finally { ArchiveUtils.closeQuietly(fos); } }
[ "public", "static", "void", "storeProperties", "(", "Properties", "p", ",", "File", "file", ")", "throws", "IOException", "{", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "file", ")", ";", "try", "{", "p", ".", "store", "(", "fos", ",",...
Store Properties instance to a File @param p @param file destination File @throws IOException
[ "Store", "Properties", "instance", "to", "a", "File" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/FileUtils.java#L352-L359
36,657
iipc/webarchive-commons
src/main/java/org/archive/util/FileUtils.java
FileUtils.ensureWriteableDirectory
public static List<File> ensureWriteableDirectory(List<File> dirs) throws IOException { for (Iterator<File> i = dirs.iterator(); i.hasNext();) { FileUtils.ensureWriteableDirectory(i.next()); } return dirs; }
java
public static List<File> ensureWriteableDirectory(List<File> dirs) throws IOException { for (Iterator<File> i = dirs.iterator(); i.hasNext();) { FileUtils.ensureWriteableDirectory(i.next()); } return dirs; }
[ "public", "static", "List", "<", "File", ">", "ensureWriteableDirectory", "(", "List", "<", "File", ">", "dirs", ")", "throws", "IOException", "{", "for", "(", "Iterator", "<", "File", ">", "i", "=", "dirs", ".", "iterator", "(", ")", ";", "i", ".", ...
Ensure writeable directories. If doesn't exist, we attempt creation. @param dirs List of Files to test. @return The passed <code>dirs</code>. @exception IOException If passed directory does not exist and is not createable, or directory is not writeable or is not a directory.
[ "Ensure", "writeable", "directories", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/FileUtils.java#L652-L658
36,658
iipc/webarchive-commons
src/main/java/org/archive/util/FileUtils.java
FileUtils.ensureWriteableDirectory
public static File ensureWriteableDirectory(File dir) throws IOException { if (!dir.exists()) { boolean success = dir.mkdirs(); if (!success) { throw new IOException("Failed to create directory: " + dir); } } else { if (!dir.canWrite()) { throw new IOException("Dir " + dir.getAbsolutePath() + " not writeable."); } else if (!dir.isDirectory()) { throw new IOException("Dir " + dir.getAbsolutePath() + " is not a directory."); } } return dir; }
java
public static File ensureWriteableDirectory(File dir) throws IOException { if (!dir.exists()) { boolean success = dir.mkdirs(); if (!success) { throw new IOException("Failed to create directory: " + dir); } } else { if (!dir.canWrite()) { throw new IOException("Dir " + dir.getAbsolutePath() + " not writeable."); } else if (!dir.isDirectory()) { throw new IOException("Dir " + dir.getAbsolutePath() + " is not a directory."); } } return dir; }
[ "public", "static", "File", "ensureWriteableDirectory", "(", "File", "dir", ")", "throws", "IOException", "{", "if", "(", "!", "dir", ".", "exists", "(", ")", ")", "{", "boolean", "success", "=", "dir", ".", "mkdirs", "(", ")", ";", "if", "(", "!", "...
Ensure writeable directory. If doesn't exist, we attempt creation. @param dir Directory to test for exitence and is writeable. @return The passed <code>dir</code>. @exception IOException If passed directory does not exist and is not createable, or directory is not writeable or is not a directory.
[ "Ensure", "writeable", "directory", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/FileUtils.java#L672-L690
36,659
iipc/webarchive-commons
src/main/java/org/archive/util/Recorder.java
Recorder.inputWrap
public InputStream inputWrap(InputStream is) throws IOException { logger.fine(Thread.currentThread().getName() + " wrapping input"); // discard any state from previously-recorded input this.characterEncoding = null; this.inputIsChunked = false; this.contentEncoding = null; this.ris.open(is); return this.ris; }
java
public InputStream inputWrap(InputStream is) throws IOException { logger.fine(Thread.currentThread().getName() + " wrapping input"); // discard any state from previously-recorded input this.characterEncoding = null; this.inputIsChunked = false; this.contentEncoding = null; this.ris.open(is); return this.ris; }
[ "public", "InputStream", "inputWrap", "(", "InputStream", "is", ")", "throws", "IOException", "{", "logger", ".", "fine", "(", "Thread", ".", "currentThread", "(", ")", ".", "getName", "(", ")", "+", "\" wrapping input\"", ")", ";", "// discard any state from pr...
Wrap the provided stream with the internal RecordingInputStream open() throws an exception if RecordingInputStream is already open. @param is InputStream to wrap. @return The input stream wrapper which itself is an input stream. Pass this in place of the passed stream so input can be recorded. @throws IOException
[ "Wrap", "the", "provided", "stream", "with", "the", "internal", "RecordingInputStream" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/Recorder.java#L176-L187
36,660
iipc/webarchive-commons
src/main/java/org/archive/util/Recorder.java
Recorder.close
public void close() { logger.fine(Thread.currentThread().getName() + " closing"); try { this.ris.close(); } catch (IOException e) { // TODO: Can we not let the exception out of here and report it // higher up in the caller? DevUtils.logger.log(Level.SEVERE, "close() ris" + DevUtils.extraInfo(), e); } try { this.ros.close(); } catch (IOException e) { DevUtils.logger.log(Level.SEVERE, "close() ros" + DevUtils.extraInfo(), e); } }
java
public void close() { logger.fine(Thread.currentThread().getName() + " closing"); try { this.ris.close(); } catch (IOException e) { // TODO: Can we not let the exception out of here and report it // higher up in the caller? DevUtils.logger.log(Level.SEVERE, "close() ris" + DevUtils.extraInfo(), e); } try { this.ros.close(); } catch (IOException e) { DevUtils.logger.log(Level.SEVERE, "close() ros" + DevUtils.extraInfo(), e); } }
[ "public", "void", "close", "(", ")", "{", "logger", ".", "fine", "(", "Thread", ".", "currentThread", "(", ")", ".", "getName", "(", ")", "+", "\" closing\"", ")", ";", "try", "{", "this", ".", "ris", ".", "close", "(", ")", ";", "}", "catch", "(...
Close all streams.
[ "Close", "all", "streams", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/Recorder.java#L210-L226
36,661
iipc/webarchive-commons
src/main/java/org/archive/util/Recorder.java
Recorder.closeRecorders
public void closeRecorders() { try { this.ris.closeRecorder(); this.ros.closeRecorder(); } catch (IOException e) { DevUtils.warnHandle(e, "Convert to runtime exception?"); } }
java
public void closeRecorders() { try { this.ris.closeRecorder(); this.ros.closeRecorder(); } catch (IOException e) { DevUtils.warnHandle(e, "Convert to runtime exception?"); } }
[ "public", "void", "closeRecorders", "(", ")", "{", "try", "{", "this", ".", "ris", ".", "closeRecorder", "(", ")", ";", "this", ".", "ros", ".", "closeRecorder", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "DevUtils", ".", "warnHa...
Close both input and output recorders. Recorders are the output streams to which we are recording. {@link #close()} closes the stream that is being recorded and the recorder. This method explicitly closes the recorder only.
[ "Close", "both", "input", "and", "output", "recorders", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/Recorder.java#L262-L269
36,662
iipc/webarchive-commons
src/main/java/org/archive/util/Recorder.java
Recorder.delete
private void delete(String name) { File f = new File(name); if (f.exists()) { f.delete(); } }
java
private void delete(String name) { File f = new File(name); if (f.exists()) { f.delete(); } }
[ "private", "void", "delete", "(", "String", "name", ")", "{", "File", "f", "=", "new", "File", "(", "name", ")", ";", "if", "(", "f", ".", "exists", "(", ")", ")", "{", "f", ".", "delete", "(", ")", ";", "}", "}" ]
Delete file if exists. @param name Filename to delete.
[ "Delete", "file", "if", "exists", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/Recorder.java#L288-L293
36,663
iipc/webarchive-commons
src/main/java/org/archive/util/Recorder.java
Recorder.getContentReplayPrefixString
public String getContentReplayPrefixString(int size, Charset cs) { try { InputStreamReader isr = new InputStreamReader(getContentReplayInputStream(), cs); char[] chars = new char[size]; int count = isr.read(chars); isr.close(); if (count > 0) { return new String(chars,0,count); } else { return ""; } } catch (IOException e) { logger.log(Level.SEVERE,"unable to get replay prefix string", e); return ""; } }
java
public String getContentReplayPrefixString(int size, Charset cs) { try { InputStreamReader isr = new InputStreamReader(getContentReplayInputStream(), cs); char[] chars = new char[size]; int count = isr.read(chars); isr.close(); if (count > 0) { return new String(chars,0,count); } else { return ""; } } catch (IOException e) { logger.log(Level.SEVERE,"unable to get replay prefix string", e); return ""; } }
[ "public", "String", "getContentReplayPrefixString", "(", "int", "size", ",", "Charset", "cs", ")", "{", "try", "{", "InputStreamReader", "isr", "=", "new", "InputStreamReader", "(", "getContentReplayInputStream", "(", ")", ",", "cs", ")", ";", "char", "[", "]"...
Return a short prefix of the presumed-textual content as a String. @param size max length of String to return @return String prefix, or empty String (with logged exception) on any error
[ "Return", "a", "short", "prefix", "of", "the", "presumed", "-", "textual", "content", "as", "a", "String", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/Recorder.java#L509-L524
36,664
iipc/webarchive-commons
src/main/java/org/archive/util/Recorder.java
Recorder.wrapInputStreamWithHttpRecord
public static Recorder wrapInputStreamWithHttpRecord(File dir, String basename, InputStream in, String encoding) throws IOException { Recorder rec = new Recorder(dir, basename); if (encoding != null && encoding.length() > 0) { rec.setCharset(Charset.forName(encoding)); } // Do not use FastBufferedInputStream here. It does not // support mark. InputStream is = rec.inputWrap(new BufferedInputStream(in)); final int BUFFER_SIZE = 1024 * 4; byte [] buffer = new byte[BUFFER_SIZE]; while(true) { // Just read it all down. int x = is.read(buffer); if (x == -1) { break; } } is.close(); return rec; }
java
public static Recorder wrapInputStreamWithHttpRecord(File dir, String basename, InputStream in, String encoding) throws IOException { Recorder rec = new Recorder(dir, basename); if (encoding != null && encoding.length() > 0) { rec.setCharset(Charset.forName(encoding)); } // Do not use FastBufferedInputStream here. It does not // support mark. InputStream is = rec.inputWrap(new BufferedInputStream(in)); final int BUFFER_SIZE = 1024 * 4; byte [] buffer = new byte[BUFFER_SIZE]; while(true) { // Just read it all down. int x = is.read(buffer); if (x == -1) { break; } } is.close(); return rec; }
[ "public", "static", "Recorder", "wrapInputStreamWithHttpRecord", "(", "File", "dir", ",", "String", "basename", ",", "InputStream", "in", ",", "String", "encoding", ")", "throws", "IOException", "{", "Recorder", "rec", "=", "new", "Recorder", "(", "dir", ",", ...
Record the input stream for later playback by an extractor, etc. This is convenience method used to setup an artificial HttpRecorder scenario used in unit tests, etc. @param dir Directory to write backing file to. @param basename of what we're recording. @param in Stream to read. @param encoding Stream encoding. @throws IOException @return An {@link org.archive.util.Recorder}.
[ "Record", "the", "input", "stream", "for", "later", "playback", "by", "an", "extractor", "etc", ".", "This", "is", "convenience", "method", "used", "to", "setup", "an", "artificial", "HttpRecorder", "scenario", "used", "in", "unit", "tests", "etc", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/Recorder.java#L554-L575
36,665
iipc/webarchive-commons
src/main/java/org/archive/io/warc/WARCWriter.java
WARCWriter.createRecordHeader
protected String createRecordHeader(WARCRecordInfo metaRecord) throws IllegalArgumentException { final StringBuilder sb = new StringBuilder(2048/*A SWAG: TODO: Do analysis.*/); sb.append(WARC_ID).append(CRLF); sb.append(HEADER_KEY_TYPE).append(COLON_SPACE).append(metaRecord.getType()). append(CRLF); // Do not write a subject-uri if not one present. if (!StringUtils.isEmpty(metaRecord.getUrl())) { sb.append(HEADER_KEY_URI).append(COLON_SPACE). append(checkHeaderValue(metaRecord.getUrl())).append(CRLF); } sb.append(HEADER_KEY_DATE).append(COLON_SPACE). append(metaRecord.getCreate14DigitDate()).append(CRLF); if (metaRecord.getExtraHeaders() != null) { for (final Iterator<Element> i = metaRecord.getExtraHeaders().iterator(); i.hasNext();) { sb.append(i.next()).append(CRLF); } } sb.append(HEADER_KEY_ID).append(COLON_SPACE).append('<'). append(metaRecord.getRecordId().toString()).append('>').append(CRLF); if (metaRecord.getContentLength() > 0) { sb.append(CONTENT_TYPE).append(COLON_SPACE).append( checkHeaderLineMimetypeParameter(metaRecord.getMimetype())).append(CRLF); } sb.append(CONTENT_LENGTH).append(COLON_SPACE). append(Long.toString(metaRecord.getContentLength())).append(CRLF); return sb.toString(); }
java
protected String createRecordHeader(WARCRecordInfo metaRecord) throws IllegalArgumentException { final StringBuilder sb = new StringBuilder(2048/*A SWAG: TODO: Do analysis.*/); sb.append(WARC_ID).append(CRLF); sb.append(HEADER_KEY_TYPE).append(COLON_SPACE).append(metaRecord.getType()). append(CRLF); // Do not write a subject-uri if not one present. if (!StringUtils.isEmpty(metaRecord.getUrl())) { sb.append(HEADER_KEY_URI).append(COLON_SPACE). append(checkHeaderValue(metaRecord.getUrl())).append(CRLF); } sb.append(HEADER_KEY_DATE).append(COLON_SPACE). append(metaRecord.getCreate14DigitDate()).append(CRLF); if (metaRecord.getExtraHeaders() != null) { for (final Iterator<Element> i = metaRecord.getExtraHeaders().iterator(); i.hasNext();) { sb.append(i.next()).append(CRLF); } } sb.append(HEADER_KEY_ID).append(COLON_SPACE).append('<'). append(metaRecord.getRecordId().toString()).append('>').append(CRLF); if (metaRecord.getContentLength() > 0) { sb.append(CONTENT_TYPE).append(COLON_SPACE).append( checkHeaderLineMimetypeParameter(metaRecord.getMimetype())).append(CRLF); } sb.append(CONTENT_LENGTH).append(COLON_SPACE). append(Long.toString(metaRecord.getContentLength())).append(CRLF); return sb.toString(); }
[ "protected", "String", "createRecordHeader", "(", "WARCRecordInfo", "metaRecord", ")", "throws", "IllegalArgumentException", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "2048", "/*A SWAG: TODO: Do analysis.*/", ")", ";", "sb", ".", "append", ...
final ANVLRecord xtraHeaders, final long contentLength)
[ "final", "ANVLRecord", "xtraHeaders", "final", "long", "contentLength", ")" ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/warc/WARCWriter.java#L184-L214
36,666
iipc/webarchive-commons
src/main/java/org/archive/util/TextUtils.java
TextUtils.getMatcher
public static Matcher getMatcher(String pattern, CharSequence input) { if (pattern == null) { throw new IllegalArgumentException("String 'pattern' must not be null"); } input = new InterruptibleCharSequence(input); final Map<String,Matcher> matchers = TL_MATCHER_MAP.get(); Matcher m = (Matcher)matchers.get(pattern); if(m == null) { m = PATTERNS.getUnchecked(pattern).matcher(input); } else { matchers.put(pattern,null); m.reset(input); } return m; }
java
public static Matcher getMatcher(String pattern, CharSequence input) { if (pattern == null) { throw new IllegalArgumentException("String 'pattern' must not be null"); } input = new InterruptibleCharSequence(input); final Map<String,Matcher> matchers = TL_MATCHER_MAP.get(); Matcher m = (Matcher)matchers.get(pattern); if(m == null) { m = PATTERNS.getUnchecked(pattern).matcher(input); } else { matchers.put(pattern,null); m.reset(input); } return m; }
[ "public", "static", "Matcher", "getMatcher", "(", "String", "pattern", ",", "CharSequence", "input", ")", "{", "if", "(", "pattern", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"String 'pattern' must not be null\"", ")", ";", "}", ...
Get a matcher object for a precompiled regex pattern. This method tries to reuse Matcher objects for efficiency. It can hold for recycling one Matcher per pattern per thread. Matchers retrieved should be returned for reuse via the recycleMatcher() method, but no errors will occur if they are not. This method is a hotspot frequently accessed. @param pattern the string pattern to use @param input the character sequence the matcher should be using @return a matcher object loaded with the submitted character sequence
[ "Get", "a", "matcher", "object", "for", "a", "precompiled", "regex", "pattern", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/TextUtils.java#L80-L94
36,667
iipc/webarchive-commons
src/main/java/org/archive/util/TextUtils.java
TextUtils.replaceAll
public static String replaceAll( String pattern, CharSequence input, String replacement) { input = new InterruptibleCharSequence(input); Matcher m = getMatcher(pattern, input); String res = m.replaceAll(replacement); recycleMatcher(m); return res; }
java
public static String replaceAll( String pattern, CharSequence input, String replacement) { input = new InterruptibleCharSequence(input); Matcher m = getMatcher(pattern, input); String res = m.replaceAll(replacement); recycleMatcher(m); return res; }
[ "public", "static", "String", "replaceAll", "(", "String", "pattern", ",", "CharSequence", "input", ",", "String", "replacement", ")", "{", "input", "=", "new", "InterruptibleCharSequence", "(", "input", ")", ";", "Matcher", "m", "=", "getMatcher", "(", "patte...
Utility method using a precompiled pattern instead of using the replaceAll method of the String class. This method will also be reusing Matcher objects. @see java.util.regex.Pattern @param pattern precompiled Pattern to match against @param input the character sequence to check @param replacement the String to substitute every match with @return the String with all the matches substituted
[ "Utility", "method", "using", "a", "precompiled", "pattern", "instead", "of", "using", "the", "replaceAll", "method", "of", "the", "String", "class", ".", "This", "method", "will", "also", "be", "reusing", "Matcher", "objects", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/TextUtils.java#L114-L121
36,668
iipc/webarchive-commons
src/main/java/org/archive/util/TextUtils.java
TextUtils.matches
public static boolean matches(String pattern, CharSequence input) { input = new InterruptibleCharSequence(input); Matcher m = getMatcher(pattern, input); boolean res = m.matches(); recycleMatcher(m); return res; }
java
public static boolean matches(String pattern, CharSequence input) { input = new InterruptibleCharSequence(input); Matcher m = getMatcher(pattern, input); boolean res = m.matches(); recycleMatcher(m); return res; }
[ "public", "static", "boolean", "matches", "(", "String", "pattern", ",", "CharSequence", "input", ")", "{", "input", "=", "new", "InterruptibleCharSequence", "(", "input", ")", ";", "Matcher", "m", "=", "getMatcher", "(", "pattern", ",", "input", ")", ";", ...
Utility method using a precompiled pattern instead of using the matches method of the String class. This method will also be reusing Matcher objects. @see java.util.regex.Pattern @param pattern precompiled Pattern to match against @param input the character sequence to check @return true if character sequence matches
[ "Utility", "method", "using", "a", "precompiled", "pattern", "instead", "of", "using", "the", "matches", "method", "of", "the", "String", "class", ".", "This", "method", "will", "also", "be", "reusing", "Matcher", "objects", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/TextUtils.java#L153-L159
36,669
iipc/webarchive-commons
src/main/java/org/archive/util/TextUtils.java
TextUtils.split
public static String[] split(String pattern, CharSequence input) { input = new InterruptibleCharSequence(input); Matcher m = getMatcher(pattern,input); String[] retVal = m.pattern().split(input); recycleMatcher(m); return retVal; }
java
public static String[] split(String pattern, CharSequence input) { input = new InterruptibleCharSequence(input); Matcher m = getMatcher(pattern,input); String[] retVal = m.pattern().split(input); recycleMatcher(m); return retVal; }
[ "public", "static", "String", "[", "]", "split", "(", "String", "pattern", ",", "CharSequence", "input", ")", "{", "input", "=", "new", "InterruptibleCharSequence", "(", "input", ")", ";", "Matcher", "m", "=", "getMatcher", "(", "pattern", ",", "input", ")...
Utility method using a precompiled pattern instead of using the split method of the String class. @see java.util.regex.Pattern @param pattern precompiled Pattern to split by @param input the character sequence to split @return array of Strings split by pattern
[ "Utility", "method", "using", "a", "precompiled", "pattern", "instead", "of", "using", "the", "split", "method", "of", "the", "String", "class", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/TextUtils.java#L170-L176
36,670
iipc/webarchive-commons
src/main/java/org/archive/util/TextUtils.java
TextUtils.unescapeHtml
public static CharSequence unescapeHtml(final CharSequence cs) { if (cs == null) { return cs; } return StringEscapeUtils.unescapeHtml(cs.toString()); }
java
public static CharSequence unescapeHtml(final CharSequence cs) { if (cs == null) { return cs; } return StringEscapeUtils.unescapeHtml(cs.toString()); }
[ "public", "static", "CharSequence", "unescapeHtml", "(", "final", "CharSequence", "cs", ")", "{", "if", "(", "cs", "==", "null", ")", "{", "return", "cs", ";", "}", "return", "StringEscapeUtils", ".", "unescapeHtml", "(", "cs", ".", "toString", "(", ")", ...
Replaces HTML Entity Encodings. @param cs The CharSequence to remove html codes from @return the same CharSequence or an escaped String.
[ "Replaces", "HTML", "Entity", "Encodings", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/TextUtils.java#L251-L257
36,671
iipc/webarchive-commons
src/main/java/org/archive/util/TextUtils.java
TextUtils.urlEscape
@SuppressWarnings("deprecation") public static String urlEscape(String s) { try { return URLEncoder.encode(s,"UTF8"); } catch (UnsupportedEncodingException e) { // should be impossible; all JVMs must support UTF8 // but have a fallback just in case return URLEncoder.encode(s); } }
java
@SuppressWarnings("deprecation") public static String urlEscape(String s) { try { return URLEncoder.encode(s,"UTF8"); } catch (UnsupportedEncodingException e) { // should be impossible; all JVMs must support UTF8 // but have a fallback just in case return URLEncoder.encode(s); } }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "static", "String", "urlEscape", "(", "String", "s", ")", "{", "try", "{", "return", "URLEncoder", ".", "encode", "(", "s", ",", "\"UTF8\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingExce...
Exception- and warning-free URL-escaping utility method. @param s String to escape @return URL-escaped string
[ "Exception", "-", "and", "warning", "-", "free", "URL", "-", "escaping", "utility", "method", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/TextUtils.java#L282-L291
36,672
iipc/webarchive-commons
src/main/java/org/archive/util/TextUtils.java
TextUtils.urlUnescape
@SuppressWarnings("deprecation") public static String urlUnescape(String s) { try { return URLDecoder.decode(s, "UTF8"); } catch (UnsupportedEncodingException e) { // should be impossible; all JVMs must support UTF8 // but have a fallback just in case return URLDecoder.decode(s); } }
java
@SuppressWarnings("deprecation") public static String urlUnescape(String s) { try { return URLDecoder.decode(s, "UTF8"); } catch (UnsupportedEncodingException e) { // should be impossible; all JVMs must support UTF8 // but have a fallback just in case return URLDecoder.decode(s); } }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "static", "String", "urlUnescape", "(", "String", "s", ")", "{", "try", "{", "return", "URLDecoder", ".", "decode", "(", "s", ",", "\"UTF8\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingEx...
Exception- and warning-free URL-unescaping utility method. @param s String do unescape @return URL-unescaped String
[ "Exception", "-", "and", "warning", "-", "free", "URL", "-", "unescaping", "utility", "method", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/TextUtils.java#L299-L308
36,673
iipc/webarchive-commons
src/main/java/org/archive/util/PrefixSet.java
PrefixSet.containsPrefixOf
public boolean containsPrefixOf(String s) { SortedSet<String> sub = headSet(s); // because redundant prefixes have been eliminated, // only a test against last item in headSet is necessary if (!sub.isEmpty() && s.startsWith((String)sub.last())) { return true; // prefix substring exists } // else: might still exist exactly (headSet does not contain boundary) return contains(s); // exact string exists, or no prefix is there }
java
public boolean containsPrefixOf(String s) { SortedSet<String> sub = headSet(s); // because redundant prefixes have been eliminated, // only a test against last item in headSet is necessary if (!sub.isEmpty() && s.startsWith((String)sub.last())) { return true; // prefix substring exists } // else: might still exist exactly (headSet does not contain boundary) return contains(s); // exact string exists, or no prefix is there }
[ "public", "boolean", "containsPrefixOf", "(", "String", "s", ")", "{", "SortedSet", "<", "String", ">", "sub", "=", "headSet", "(", "s", ")", ";", "// because redundant prefixes have been eliminated,\r", "// only a test against last item in headSet is necessary\r", "if", ...
Test whether the given String is prefixed by one of this set's entries. @param s @return True if contains prefix.
[ "Test", "whether", "the", "given", "String", "is", "prefixed", "by", "one", "of", "this", "set", "s", "entries", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/PrefixSet.java#L43-L51
36,674
iipc/webarchive-commons
src/main/java/org/archive/util/DevUtils.java
DevUtils.warnHandle
public static void warnHandle(Throwable ex, String note) { logger.warning(TextUtils.exceptionToString(note, ex)); }
java
public static void warnHandle(Throwable ex, String note) { logger.warning(TextUtils.exceptionToString(note, ex)); }
[ "public", "static", "void", "warnHandle", "(", "Throwable", "ex", ",", "String", "note", ")", "{", "logger", ".", "warning", "(", "TextUtils", ".", "exceptionToString", "(", "note", ",", "ex", ")", ")", ";", "}" ]
Log a warning message to the logger 'org.archive.util.DevUtils' made of the passed 'note' and a stack trace based off passed exception. @param ex Exception we print a stacktrace on. @param note Message to print ahead of the stacktrace.
[ "Log", "a", "warning", "message", "to", "the", "logger", "org", ".", "archive", ".", "util", ".", "DevUtils", "made", "of", "the", "passed", "note", "and", "a", "stack", "trace", "based", "off", "passed", "exception", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/DevUtils.java#L46-L48
36,675
iipc/webarchive-commons
src/main/java/org/archive/util/MimetypeUtils.java
MimetypeUtils.truncate
public static String truncate(String contentType) { if (contentType == null) { contentType = NO_TYPE_MIMETYPE; } else { Matcher matcher = TRUNCATION_REGEX.matcher(contentType); if (matcher.matches()) { contentType = matcher.group(1); } else { contentType = NO_TYPE_MIMETYPE; } } return contentType; }
java
public static String truncate(String contentType) { if (contentType == null) { contentType = NO_TYPE_MIMETYPE; } else { Matcher matcher = TRUNCATION_REGEX.matcher(contentType); if (matcher.matches()) { contentType = matcher.group(1); } else { contentType = NO_TYPE_MIMETYPE; } } return contentType; }
[ "public", "static", "String", "truncate", "(", "String", "contentType", ")", "{", "if", "(", "contentType", "==", "null", ")", "{", "contentType", "=", "NO_TYPE_MIMETYPE", ";", "}", "else", "{", "Matcher", "matcher", "=", "TRUNCATION_REGEX", ".", "matcher", ...
Truncate passed mimetype. Ensure no spaces. Strip encoding. Truncation required by ARC files. <p>Truncate at delimiters [;, ]. Truncate multi-part content type header at ';'. Apache httpclient collapses values of multiple instances of the header into one comma-separated value,therefore truncated at ','. Current ia_tools that work with arc files expect 5-column space-separated meta-lines, therefore truncate at ' '. @param contentType Raw content-type. @return Computed content-type made from passed content-type after running it through a set of rules.
[ "Truncate", "passed", "mimetype", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/MimetypeUtils.java#L61-L74
36,676
iipc/webarchive-commons
src/main/java/org/archive/io/Endian.java
Endian.littleChar
public static char littleChar(InputStream input) throws IOException { int lo = input.read(); if (lo < 0) { throw new EOFException(); } int hi = input.read(); if (hi < 0) { throw new EOFException(); } return (char)((hi << 8) | lo); }
java
public static char littleChar(InputStream input) throws IOException { int lo = input.read(); if (lo < 0) { throw new EOFException(); } int hi = input.read(); if (hi < 0) { throw new EOFException(); } return (char)((hi << 8) | lo); }
[ "public", "static", "char", "littleChar", "(", "InputStream", "input", ")", "throws", "IOException", "{", "int", "lo", "=", "input", ".", "read", "(", ")", ";", "if", "(", "lo", "<", "0", ")", "{", "throw", "new", "EOFException", "(", ")", ";", "}", ...
Reads the next little-endian unsigned 16 bit integer from the given stream. @param input the input stream to read from @return the next 16-bit little-endian integer @throws IOException if an IO error occurs
[ "Reads", "the", "next", "little", "-", "endian", "unsigned", "16", "bit", "integer", "from", "the", "given", "stream", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/Endian.java#L50-L60
36,677
iipc/webarchive-commons
src/main/java/org/archive/io/Endian.java
Endian.littleInt
public static int littleInt(InputStream input) throws IOException { char lo = littleChar(input); char hi = littleChar(input); return (hi << 16) | lo; }
java
public static int littleInt(InputStream input) throws IOException { char lo = littleChar(input); char hi = littleChar(input); return (hi << 16) | lo; }
[ "public", "static", "int", "littleInt", "(", "InputStream", "input", ")", "throws", "IOException", "{", "char", "lo", "=", "littleChar", "(", "input", ")", ";", "char", "hi", "=", "littleChar", "(", "input", ")", ";", "return", "(", "hi", "<<", "16", "...
Reads the next little-endian signed 32-bit integer from the given stream. @param input the input stream to read from @return the next 32-bit little-endian integer @throws IOException if an IO error occurs
[ "Reads", "the", "next", "little", "-", "endian", "signed", "32", "-", "bit", "integer", "from", "the", "given", "stream", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/Endian.java#L84-L88
36,678
iipc/webarchive-commons
src/main/java/org/archive/io/Endian.java
Endian.bigChar
public static char bigChar(InputStream input) throws IOException { int hi = input.read(); if (hi < 0) { throw new EOFException(); } int lo = input.read(); if (lo < 0) { throw new EOFException(); } return (char)((hi << 8) | lo); }
java
public static char bigChar(InputStream input) throws IOException { int hi = input.read(); if (hi < 0) { throw new EOFException(); } int lo = input.read(); if (lo < 0) { throw new EOFException(); } return (char)((hi << 8) | lo); }
[ "public", "static", "char", "bigChar", "(", "InputStream", "input", ")", "throws", "IOException", "{", "int", "hi", "=", "input", ".", "read", "(", ")", ";", "if", "(", "hi", "<", "0", ")", "{", "throw", "new", "EOFException", "(", ")", ";", "}", "...
Reads the next big-endian unsigned 16 bit integer from the given stream. @param input the input stream to read from @return the next 16-bit big-endian integer @throws IOException if an IO error occurs
[ "Reads", "the", "next", "big", "-", "endian", "unsigned", "16", "bit", "integer", "from", "the", "given", "stream", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/Endian.java#L99-L109
36,679
iipc/webarchive-commons
src/main/java/org/archive/io/Endian.java
Endian.bigInt
public static int bigInt(InputStream input) throws IOException { char hi = bigChar(input); char lo = bigChar(input); return (hi << 16) | lo; }
java
public static int bigInt(InputStream input) throws IOException { char hi = bigChar(input); char lo = bigChar(input); return (hi << 16) | lo; }
[ "public", "static", "int", "bigInt", "(", "InputStream", "input", ")", "throws", "IOException", "{", "char", "hi", "=", "bigChar", "(", "input", ")", ";", "char", "lo", "=", "bigChar", "(", "input", ")", ";", "return", "(", "hi", "<<", "16", ")", "|"...
Reads the next big-endian signed 32-bit integer from the given stream. @param input the input stream to read from @return the next 32-bit big-endian integer @throws IOException if an IO error occurs
[ "Reads", "the", "next", "big", "-", "endian", "signed", "32", "-", "bit", "integer", "from", "the", "given", "stream", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/Endian.java#L120-L124
36,680
iipc/webarchive-commons
src/main/java/org/archive/io/ObjectPlusFilesInputStream.java
ObjectPlusFilesInputStream.restoreFile
public void restoreFile(File destination) throws IOException { String nameAsStored = readUTF(); long lengthAtStoreTime = readLong(); File storedFile = new File(getAuxiliaryDirectory(),nameAsStored); FileUtils.copyFile(storedFile, destination, lengthAtStoreTime); }
java
public void restoreFile(File destination) throws IOException { String nameAsStored = readUTF(); long lengthAtStoreTime = readLong(); File storedFile = new File(getAuxiliaryDirectory(),nameAsStored); FileUtils.copyFile(storedFile, destination, lengthAtStoreTime); }
[ "public", "void", "restoreFile", "(", "File", "destination", ")", "throws", "IOException", "{", "String", "nameAsStored", "=", "readUTF", "(", ")", ";", "long", "lengthAtStoreTime", "=", "readLong", "(", ")", ";", "File", "storedFile", "=", "new", "File", "(...
Restore a file from storage, using the name and length info on the serialization stream and the file from the current auxiliary directory, to the given File. @param destination @throws IOException
[ "Restore", "a", "file", "from", "storage", "using", "the", "name", "and", "length", "info", "on", "the", "serialization", "stream", "and", "the", "file", "from", "the", "current", "auxiliary", "directory", "to", "the", "given", "File", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/ObjectPlusFilesInputStream.java#L94-L99
36,681
iipc/webarchive-commons
src/main/java/org/archive/io/arc/ARCRecord.java
ARCRecord.getTokenizedHeaderLine
private int getTokenizedHeaderLine(final InputStream stream, List<String> list) throws IOException { // Preallocate usual line size. StringBuilder buffer = new StringBuilder(2048 + 20); int read = 0; int previous = -1; for (int c = -1; true;) { previous = c; c = stream.read(); if (c == -1) { throw new RecoverableIOException("Hit EOF before header EOL."); } c &= 0xff; read++; if (read > MAX_HEADER_LINE_LENGTH) { throw new IOException("Header line longer than max allowed " + " -- " + String.valueOf(MAX_HEADER_LINE_LENGTH) + " -- or passed buffer doesn't contain a line (Read: " + buffer.length() + "). Here's" + " some of what was read: " + buffer.substring(0, Math.min(buffer.length(), 256))); } if (c == LINE_SEPARATOR) { if (buffer.length() == 0) { // Empty line at start of buffer. Skip it and try again. continue; } if (list != null) { list.add(buffer.toString()); } // LOOP TERMINATION. break; } else if (c == HEADER_FIELD_SEPARATOR) { if (!isStrict() && previous == HEADER_FIELD_SEPARATOR) { // Early ARCs sometimes had multiple spaces between fields. continue; } if (list != null) { list.add(buffer.toString()); } // reset to empty buffer.setLength(0); } else { buffer.append((char)c); } } // List must have at least 3 elements in it and no more than 10. If // it has other than this, then bogus parse. if (list != null && (list.size() < 3 || list.size() > 100)) { throw new IOException("Unparseable header line: " + list); } // save verbatim header String this.headerString = StringUtils.join(list," "); return read; }
java
private int getTokenizedHeaderLine(final InputStream stream, List<String> list) throws IOException { // Preallocate usual line size. StringBuilder buffer = new StringBuilder(2048 + 20); int read = 0; int previous = -1; for (int c = -1; true;) { previous = c; c = stream.read(); if (c == -1) { throw new RecoverableIOException("Hit EOF before header EOL."); } c &= 0xff; read++; if (read > MAX_HEADER_LINE_LENGTH) { throw new IOException("Header line longer than max allowed " + " -- " + String.valueOf(MAX_HEADER_LINE_LENGTH) + " -- or passed buffer doesn't contain a line (Read: " + buffer.length() + "). Here's" + " some of what was read: " + buffer.substring(0, Math.min(buffer.length(), 256))); } if (c == LINE_SEPARATOR) { if (buffer.length() == 0) { // Empty line at start of buffer. Skip it and try again. continue; } if (list != null) { list.add(buffer.toString()); } // LOOP TERMINATION. break; } else if (c == HEADER_FIELD_SEPARATOR) { if (!isStrict() && previous == HEADER_FIELD_SEPARATOR) { // Early ARCs sometimes had multiple spaces between fields. continue; } if (list != null) { list.add(buffer.toString()); } // reset to empty buffer.setLength(0); } else { buffer.append((char)c); } } // List must have at least 3 elements in it and no more than 10. If // it has other than this, then bogus parse. if (list != null && (list.size() < 3 || list.size() > 100)) { throw new IOException("Unparseable header line: " + list); } // save verbatim header String this.headerString = StringUtils.join(list," "); return read; }
[ "private", "int", "getTokenizedHeaderLine", "(", "final", "InputStream", "stream", ",", "List", "<", "String", ">", "list", ")", "throws", "IOException", "{", "// Preallocate usual line size.", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", "2048", "+"...
Get a record header line as list of tokens. We keep reading till we find a LINE_SEPARATOR or we reach the end of file w/o finding a LINE_SEPARATOR or the line length is crazy. @param stream InputStream to read from. @param list Empty list that gets filled w/ string tokens. @return Count of characters read. @exception IOException If problem reading stream or no line separator found or EOF before EOL or we didn't get minimum header fields.
[ "Get", "a", "record", "header", "line", "as", "list", "of", "tokens", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/arc/ARCRecord.java#L292-L351
36,682
iipc/webarchive-commons
src/main/java/org/archive/io/arc/ARCRecord.java
ARCRecord.skipHttpHeader
public void skipHttpHeader() throws IOException { if (this.httpHeaderStream != null) { // Empty the httpHeaderStream for (int available = this.httpHeaderStream.available(); this.httpHeaderStream != null && (available = this.httpHeaderStream.available()) > 0;) { // We should be in this loop once only we should only do this // buffer allocation once. byte [] buffer = new byte[available]; // The read nulls out httpHeaderStream when done with it so // need check for null in the loop control line. read(buffer, 0, available); } } }
java
public void skipHttpHeader() throws IOException { if (this.httpHeaderStream != null) { // Empty the httpHeaderStream for (int available = this.httpHeaderStream.available(); this.httpHeaderStream != null && (available = this.httpHeaderStream.available()) > 0;) { // We should be in this loop once only we should only do this // buffer allocation once. byte [] buffer = new byte[available]; // The read nulls out httpHeaderStream when done with it so // need check for null in the loop control line. read(buffer, 0, available); } } }
[ "public", "void", "skipHttpHeader", "(", ")", "throws", "IOException", "{", "if", "(", "this", ".", "httpHeaderStream", "!=", "null", ")", "{", "// Empty the httpHeaderStream", "for", "(", "int", "available", "=", "this", ".", "httpHeaderStream", ".", "available...
Skip over the the http header if one present. Subsequent reads will get the body. <p>Calling this method in the midst of reading the header will make for strange results. Otherwise, safe to call at any time though before reading any of the arc record content is only time that it makes sense. <p>After calling this method, you can call {@link #getHttpHeaders()} to get the read http header. @throws IOException
[ "Skip", "over", "the", "the", "http", "header", "if", "one", "present", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/arc/ARCRecord.java#L521-L535
36,683
iipc/webarchive-commons
src/main/java/org/archive/url/UsableURIFactory.java
UsableURIFactory.validityCheck
protected UsableURI validityCheck(UsableURI uuri) throws URIException { if (uuri.getRawURI().length > UsableURI.MAX_URL_LENGTH) { throw new URIException("Created (escaped) uuri > " + UsableURI.MAX_URL_LENGTH +": "+uuri.toString()); } return uuri; }
java
protected UsableURI validityCheck(UsableURI uuri) throws URIException { if (uuri.getRawURI().length > UsableURI.MAX_URL_LENGTH) { throw new URIException("Created (escaped) uuri > " + UsableURI.MAX_URL_LENGTH +": "+uuri.toString()); } return uuri; }
[ "protected", "UsableURI", "validityCheck", "(", "UsableURI", "uuri", ")", "throws", "URIException", "{", "if", "(", "uuri", ".", "getRawURI", "(", ")", ".", "length", ">", "UsableURI", ".", "MAX_URL_LENGTH", ")", "{", "throw", "new", "URIException", "(", "\"...
Check the generated UURI. At the least look at length of uuri string. We were seeing case where before escaping, string was &lt; MAX_URL_LENGTH but after was &gt;. Letting out a too-big message was causing us troubles later down the processing chain. @param uuri Created uuri to check. @return The passed <code>uuri</code> so can easily inline this check. @throws URIException
[ "Check", "the", "generated", "UURI", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/url/UsableURIFactory.java#L324-L330
36,684
iipc/webarchive-commons
src/main/java/org/archive/url/UsableURIFactory.java
UsableURIFactory.fixupAuthority
private String fixupAuthority(String uriAuthority, String charset) throws URIException { // Lowercase the host part of the uriAuthority; don't destroy any // userinfo capitalizations. Make sure no illegal characters in // domainlabel substring of the uri authority. if (uriAuthority != null) { // Get rid of any trailing escaped spaces: // http://www.archive.org%20. Rare but happens. // TODO: reevaluate: do IE or firefox do such mid-URI space-removal? // if not, we shouldn't either. while(uriAuthority.endsWith(ESCAPED_SPACE)) { uriAuthority = uriAuthority.substring(0,uriAuthority.length()-3); } // lowercase & IDN-punycode only the domain portion int atIndex = uriAuthority.indexOf(COMMERCIAL_AT); int portColonIndex = uriAuthority.indexOf(COLON,(atIndex<0)?0:atIndex); if(atIndex<0 && portColonIndex<0) { // most common case: neither userinfo nor port return fixupDomainlabel(uriAuthority); } else if (atIndex<0 && portColonIndex>-1) { // next most common: port but no userinfo String domain = fixupDomainlabel(uriAuthority.substring(0,portColonIndex)); String port = uriAuthority.substring(portColonIndex); return domain + port; } else if (atIndex>-1 && portColonIndex<0) { // uncommon: userinfo, no port String userinfo = ensureMinimalEscaping(uriAuthority.substring(0,atIndex+1),charset); String domain = fixupDomainlabel(uriAuthority.substring(atIndex+1)); return userinfo + domain; } else { // uncommon: userinfo, port String userinfo = ensureMinimalEscaping(uriAuthority.substring(0,atIndex+1),charset); String domain = fixupDomainlabel(uriAuthority.substring(atIndex+1,portColonIndex)); String port = uriAuthority.substring(portColonIndex); return userinfo + domain + port; } } return uriAuthority; }
java
private String fixupAuthority(String uriAuthority, String charset) throws URIException { // Lowercase the host part of the uriAuthority; don't destroy any // userinfo capitalizations. Make sure no illegal characters in // domainlabel substring of the uri authority. if (uriAuthority != null) { // Get rid of any trailing escaped spaces: // http://www.archive.org%20. Rare but happens. // TODO: reevaluate: do IE or firefox do such mid-URI space-removal? // if not, we shouldn't either. while(uriAuthority.endsWith(ESCAPED_SPACE)) { uriAuthority = uriAuthority.substring(0,uriAuthority.length()-3); } // lowercase & IDN-punycode only the domain portion int atIndex = uriAuthority.indexOf(COMMERCIAL_AT); int portColonIndex = uriAuthority.indexOf(COLON,(atIndex<0)?0:atIndex); if(atIndex<0 && portColonIndex<0) { // most common case: neither userinfo nor port return fixupDomainlabel(uriAuthority); } else if (atIndex<0 && portColonIndex>-1) { // next most common: port but no userinfo String domain = fixupDomainlabel(uriAuthority.substring(0,portColonIndex)); String port = uriAuthority.substring(portColonIndex); return domain + port; } else if (atIndex>-1 && portColonIndex<0) { // uncommon: userinfo, no port String userinfo = ensureMinimalEscaping(uriAuthority.substring(0,atIndex+1),charset); String domain = fixupDomainlabel(uriAuthority.substring(atIndex+1)); return userinfo + domain; } else { // uncommon: userinfo, port String userinfo = ensureMinimalEscaping(uriAuthority.substring(0,atIndex+1),charset); String domain = fixupDomainlabel(uriAuthority.substring(atIndex+1,portColonIndex)); String port = uriAuthority.substring(portColonIndex); return userinfo + domain + port; } } return uriAuthority; }
[ "private", "String", "fixupAuthority", "(", "String", "uriAuthority", ",", "String", "charset", ")", "throws", "URIException", "{", "// Lowercase the host part of the uriAuthority; don't destroy any", "// userinfo capitalizations. Make sure no illegal characters in", "// domainlabel s...
Fixup 'authority' portion of URI, by removing any stray encoded spaces, lowercasing any domain names, and applying IDN-punycoding to Unicode domains. @param uriAuthority the authority string to fix @return fixed version @throws URIException
[ "Fixup", "authority", "portion", "of", "URI", "by", "removing", "any", "stray", "encoded", "spaces", "lowercasing", "any", "domain", "names", "and", "applying", "IDN", "-", "punycoding", "to", "Unicode", "domains", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/url/UsableURIFactory.java#L545-L583
36,685
iipc/webarchive-commons
src/main/java/org/archive/url/UsableURIFactory.java
UsableURIFactory.fixupDomainlabel
private String fixupDomainlabel(String label) throws URIException { // apply IDN-punycoding, as necessary try { // TODO: optimize: only apply when necessary, or // keep cache of recent encodings label = IDNA.toASCII(label); } catch (IDNAException e) { if(TextUtils.matches(ACCEPTABLE_ASCII_DOMAIN,label)) { // domain name has ACE prefix, leading/trailing dash, or // underscore -- but is still a name we wish to tolerate; // simply continue } else { // problematic domain: neither ASCII acceptable characters // nor IDN-punycodable, so throw exception // TODO: change to HeritrixURIException so distinguishable // from URIExceptions in library code URIException ue = new URIException(e+" "+label); ue.initCause(e); throw ue; } } label = label.toLowerCase(); return label; }
java
private String fixupDomainlabel(String label) throws URIException { // apply IDN-punycoding, as necessary try { // TODO: optimize: only apply when necessary, or // keep cache of recent encodings label = IDNA.toASCII(label); } catch (IDNAException e) { if(TextUtils.matches(ACCEPTABLE_ASCII_DOMAIN,label)) { // domain name has ACE prefix, leading/trailing dash, or // underscore -- but is still a name we wish to tolerate; // simply continue } else { // problematic domain: neither ASCII acceptable characters // nor IDN-punycodable, so throw exception // TODO: change to HeritrixURIException so distinguishable // from URIExceptions in library code URIException ue = new URIException(e+" "+label); ue.initCause(e); throw ue; } } label = label.toLowerCase(); return label; }
[ "private", "String", "fixupDomainlabel", "(", "String", "label", ")", "throws", "URIException", "{", "// apply IDN-punycoding, as necessary", "try", "{", "// TODO: optimize: only apply when necessary, or", "// keep cache of recent encodings", "label", "=", "IDNA", ".", "toASCII...
Fixup the domain label part of the authority. We're more lax than the spec. in that we allow underscores. @param label Domain label to fix. @return Return fixed domain label. @throws URIException
[ "Fixup", "the", "domain", "label", "part", "of", "the", "authority", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/url/UsableURIFactory.java#L594-L619
36,686
iipc/webarchive-commons
src/main/java/org/archive/io/arc/ARCReader.java
ARCReader.createArchiveRecord
protected ARCRecord createArchiveRecord(InputStream is, long offset) throws IOException { try { String version = super.getVersion(); ARCRecord record = new ARCRecord(is, getReaderIdentifier(), offset, isDigest(), isStrict(), isParseHttpHeaders(), isAlignedOnFirstRecord(), version); if (version != null && super.getVersion() == null) super.setVersion(version); currentRecord(record); } catch (IOException e) { if (e instanceof RecoverableIOException) { // Don't mess with RecoverableIOExceptions. Let them out. throw e; } IOException newE = new IOException(e.getMessage() + " (Offset " + offset + ")."); newE.setStackTrace(e.getStackTrace()); throw newE; } return (ARCRecord)getCurrentRecord(); }
java
protected ARCRecord createArchiveRecord(InputStream is, long offset) throws IOException { try { String version = super.getVersion(); ARCRecord record = new ARCRecord(is, getReaderIdentifier(), offset, isDigest(), isStrict(), isParseHttpHeaders(), isAlignedOnFirstRecord(), version); if (version != null && super.getVersion() == null) super.setVersion(version); currentRecord(record); } catch (IOException e) { if (e instanceof RecoverableIOException) { // Don't mess with RecoverableIOExceptions. Let them out. throw e; } IOException newE = new IOException(e.getMessage() + " (Offset " + offset + ")."); newE.setStackTrace(e.getStackTrace()); throw newE; } return (ARCRecord)getCurrentRecord(); }
[ "protected", "ARCRecord", "createArchiveRecord", "(", "InputStream", "is", ",", "long", "offset", ")", "throws", "IOException", "{", "try", "{", "String", "version", "=", "super", ".", "getVersion", "(", ")", ";", "ARCRecord", "record", "=", "new", "ARCRecord"...
Create new arc record. Encapsulate housekeeping that has to do w/ creating a new record. <p>Call this method at end of constructor to read in the arcfile header. Will be problems reading subsequent arc records if you don't since arcfile header has the list of metadata fields for all records that follow. <p>When parsing through ARCs writing out CDX info, we spend about 38% of CPU in here -- about 30% of which is in getTokenizedHeaderLine -- of which 16% is reading. @param is InputStream to use. @param offset Absolute offset into arc file. @return An arc record. @throws IOException
[ "Create", "new", "arc", "record", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/arc/ARCReader.java#L145-L166
36,687
iipc/webarchive-commons
src/main/java/org/archive/net/PublicSuffixes.java
PublicSuffixes.dump
public static void dump(Node alt, int lv, PrintWriter out) { for (int i = 0; i < lv; i++) out.print(" "); out.println(alt.cs != null ? ('"'+alt.cs.toString()+'"') : "(null)"); if (alt.branches != null) { for (Node br : alt.branches) { dump(br, lv + 1, out); } } }
java
public static void dump(Node alt, int lv, PrintWriter out) { for (int i = 0; i < lv; i++) out.print(" "); out.println(alt.cs != null ? ('"'+alt.cs.toString()+'"') : "(null)"); if (alt.branches != null) { for (Node br : alt.branches) { dump(br, lv + 1, out); } } }
[ "public", "static", "void", "dump", "(", "Node", "alt", ",", "int", "lv", ",", "PrintWriter", "out", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "lv", ";", "i", "++", ")", "out", ".", "print", "(", "\" \"", ")", ";", "out", "....
utility function for dumping prefix tree structure. intended for debug use. @param alt root of prefix tree. @param lv indent level. 0 for root (no indent). @param out writer to send output to.
[ "utility", "function", "for", "dumping", "prefix", "tree", "structure", ".", "intended", "for", "debug", "use", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/net/PublicSuffixes.java#L240-L249
36,688
iipc/webarchive-commons
src/main/java/org/archive/net/PublicSuffixes.java
PublicSuffixes.reduceSurtToAssignmentLevel
public static String reduceSurtToAssignmentLevel(String surt) { Matcher matcher = TextUtils.getMatcher( getTopmostAssignedSurtPrefixRegex(), surt); if (matcher.find()) { surt = matcher.group(); } TextUtils.recycleMatcher(matcher); return surt; }
java
public static String reduceSurtToAssignmentLevel(String surt) { Matcher matcher = TextUtils.getMatcher( getTopmostAssignedSurtPrefixRegex(), surt); if (matcher.find()) { surt = matcher.group(); } TextUtils.recycleMatcher(matcher); return surt; }
[ "public", "static", "String", "reduceSurtToAssignmentLevel", "(", "String", "surt", ")", "{", "Matcher", "matcher", "=", "TextUtils", ".", "getMatcher", "(", "getTopmostAssignedSurtPrefixRegex", "(", ")", ",", "surt", ")", ";", "if", "(", "matcher", ".", "find",...
Truncate SURT to its topmost assigned domain segment; that is, the public suffix plus one segment, but as a SURT-ordered prefix. if the pattern doesn't match, the passed-in SURT is returned. @param surt SURT to truncate @return truncated-to-topmost-assigned SURT prefix
[ "Truncate", "SURT", "to", "its", "topmost", "assigned", "domain", "segment", ";", "that", "is", "the", "public", "suffix", "plus", "one", "segment", "but", "as", "a", "SURT", "-", "ordered", "prefix", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/net/PublicSuffixes.java#L354-L362
36,689
iipc/webarchive-commons
src/main/java/org/archive/io/BufferedSeekInputStream.java
BufferedSeekInputStream.buffer
private void buffer() throws IOException { int remaining = buffer.length; while (remaining > 0) { int r = input.read(buffer, buffer.length - remaining, remaining); if (r <= 0) { // Not enough information to fill the buffer offset = 0; maxOffset = buffer.length - remaining; return; } remaining -= r; } maxOffset = buffer.length; offset = 0; }
java
private void buffer() throws IOException { int remaining = buffer.length; while (remaining > 0) { int r = input.read(buffer, buffer.length - remaining, remaining); if (r <= 0) { // Not enough information to fill the buffer offset = 0; maxOffset = buffer.length - remaining; return; } remaining -= r; } maxOffset = buffer.length; offset = 0; }
[ "private", "void", "buffer", "(", ")", "throws", "IOException", "{", "int", "remaining", "=", "buffer", ".", "length", ";", "while", "(", "remaining", ">", "0", ")", "{", "int", "r", "=", "input", ".", "read", "(", "buffer", ",", "buffer", ".", "leng...
Fills the buffer. @throws IOException if an IO error occurs
[ "Fills", "the", "buffer", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/BufferedSeekInputStream.java#L78-L92
36,690
iipc/webarchive-commons
src/main/java/org/archive/io/BufferedSeekInputStream.java
BufferedSeekInputStream.position
public void position(long p) throws IOException { long blockStart = (input.position() - maxOffset) / buffer.length * buffer.length; long blockEnd = blockStart + maxOffset; if ((p >= blockStart) && (p < blockEnd)) { // Desired position is somewhere inside current buffer long adj = p - blockStart; offset = (int)adj; return; } positionDirect(p); }
java
public void position(long p) throws IOException { long blockStart = (input.position() - maxOffset) / buffer.length * buffer.length; long blockEnd = blockStart + maxOffset; if ((p >= blockStart) && (p < blockEnd)) { // Desired position is somewhere inside current buffer long adj = p - blockStart; offset = (int)adj; return; } positionDirect(p); }
[ "public", "void", "position", "(", "long", "p", ")", "throws", "IOException", "{", "long", "blockStart", "=", "(", "input", ".", "position", "(", ")", "-", "maxOffset", ")", "/", "buffer", ".", "length", "*", "buffer", ".", "length", ";", "long", "bloc...
Seeks to the given position. This method avoids re-filling the buffer if at all possible. @param p the position to set @throws IOException if an IO error occurs
[ "Seeks", "to", "the", "given", "position", ".", "This", "method", "avoids", "re", "-", "filling", "the", "buffer", "if", "at", "all", "possible", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/BufferedSeekInputStream.java#L178-L189
36,691
iipc/webarchive-commons
src/main/java/org/archive/io/BufferedSeekInputStream.java
BufferedSeekInputStream.positionDirect
private void positionDirect(long p) throws IOException { long newBlockStart = p / buffer.length * buffer.length; input.position(newBlockStart); buffer(); offset = (int)(p % buffer.length); }
java
private void positionDirect(long p) throws IOException { long newBlockStart = p / buffer.length * buffer.length; input.position(newBlockStart); buffer(); offset = (int)(p % buffer.length); }
[ "private", "void", "positionDirect", "(", "long", "p", ")", "throws", "IOException", "{", "long", "newBlockStart", "=", "p", "/", "buffer", ".", "length", "*", "buffer", ".", "length", ";", "input", ".", "position", "(", "newBlockStart", ")", ";", "buffer"...
Positions the underlying stream at the given position, then refills the buffer. @param p the position to set @throws IOException if an IO error occurs
[ "Positions", "the", "underlying", "stream", "at", "the", "given", "position", "then", "refills", "the", "buffer", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/BufferedSeekInputStream.java#L199-L204
36,692
iipc/webarchive-commons
src/main/java/org/archive/io/ArchiveReader.java
ArchiveReader.getInputStream
protected InputStream getInputStream(final File f, final long offset) throws IOException { FileInputStream fin = new FileInputStream(f); return new BufferedInputStream(fin); }
java
protected InputStream getInputStream(final File f, final long offset) throws IOException { FileInputStream fin = new FileInputStream(f); return new BufferedInputStream(fin); }
[ "protected", "InputStream", "getInputStream", "(", "final", "File", "f", ",", "final", "long", "offset", ")", "throws", "IOException", "{", "FileInputStream", "fin", "=", "new", "FileInputStream", "(", "f", ")", ";", "return", "new", "BufferedInputStream", "(", ...
Convenience method for constructors. @param f File to read. @param offset Offset at which to start reading. @return InputStream to read from. @throws IOException If failed open or fail to get a memory mapped byte buffer on file.
[ "Convenience", "method", "for", "constructors", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/ArchiveReader.java#L126-L130
36,693
iipc/webarchive-commons
src/main/java/org/archive/io/ArchiveReader.java
ArchiveReader.cleanupCurrentRecord
protected void cleanupCurrentRecord() throws IOException { if (this.currentRecord != null) { this.currentRecord.close(); gotoEOR(this.currentRecord); this.currentRecord = null; } }
java
protected void cleanupCurrentRecord() throws IOException { if (this.currentRecord != null) { this.currentRecord.close(); gotoEOR(this.currentRecord); this.currentRecord = null; } }
[ "protected", "void", "cleanupCurrentRecord", "(", ")", "throws", "IOException", "{", "if", "(", "this", ".", "currentRecord", "!=", "null", ")", "{", "this", ".", "currentRecord", ".", "close", "(", ")", ";", "gotoEOR", "(", "this", ".", "currentRecord", "...
Cleanout the current record if there is one. @throws IOException
[ "Cleanout", "the", "current", "record", "if", "there", "is", "one", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/ArchiveReader.java#L173-L179
36,694
iipc/webarchive-commons
src/main/java/org/archive/io/ArchiveReader.java
ArchiveReader.validate
public List<ArchiveRecordHeader> validate(int numRecords) throws IOException { List<ArchiveRecordHeader> hdrList = new ArrayList<ArchiveRecordHeader>(); int recordCount = 0; setStrict(true); for (Iterator<ArchiveRecord> i = iterator(); i.hasNext();) { recordCount++; ArchiveRecord r = i.next(); if (r.getHeader().getLength() <= 0 && r.getHeader().getMimetype(). equals(MimetypeUtils.NO_TYPE_MIMETYPE)) { throw new IOException("record content is empty."); } r.close(); hdrList.add(r.getHeader()); } if (numRecords != -1) { if (recordCount != numRecords) { throw new IOException("Count of records, " + Integer.toString(recordCount) + " is not equal to expected " + Integer.toString(numRecords)); } } return hdrList; }
java
public List<ArchiveRecordHeader> validate(int numRecords) throws IOException { List<ArchiveRecordHeader> hdrList = new ArrayList<ArchiveRecordHeader>(); int recordCount = 0; setStrict(true); for (Iterator<ArchiveRecord> i = iterator(); i.hasNext();) { recordCount++; ArchiveRecord r = i.next(); if (r.getHeader().getLength() <= 0 && r.getHeader().getMimetype(). equals(MimetypeUtils.NO_TYPE_MIMETYPE)) { throw new IOException("record content is empty."); } r.close(); hdrList.add(r.getHeader()); } if (numRecords != -1) { if (recordCount != numRecords) { throw new IOException("Count of records, " + Integer.toString(recordCount) + " is not equal to expected " + Integer.toString(numRecords)); } } return hdrList; }
[ "public", "List", "<", "ArchiveRecordHeader", ">", "validate", "(", "int", "numRecords", ")", "throws", "IOException", "{", "List", "<", "ArchiveRecordHeader", ">", "hdrList", "=", "new", "ArrayList", "<", "ArchiveRecordHeader", ">", "(", ")", ";", "int", "rec...
Validate the Archive file. This method iterates over the file throwing exception if it fails to successfully parse. <p>We start validation from wherever we are in the stream. @param numRecords Number of records expected. Pass -1 if number is unknown. @return List of all read metadatas. As we validate records, we add a reference to the read metadata. @throws IOException
[ "Validate", "the", "Archive", "file", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/ArchiveReader.java#L242-L269
36,695
iipc/webarchive-commons
src/main/java/org/archive/io/ArchiveReader.java
ArchiveReader.isValid
public boolean isValid() { boolean valid = false; try { validate(); valid = true; } catch(Exception e) { // File is not valid if exception thrown parsing. valid = false; } return valid; }
java
public boolean isValid() { boolean valid = false; try { validate(); valid = true; } catch(Exception e) { // File is not valid if exception thrown parsing. valid = false; } return valid; }
[ "public", "boolean", "isValid", "(", ")", "{", "boolean", "valid", "=", "false", ";", "try", "{", "validate", "(", ")", ";", "valid", "=", "true", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// File is not valid if exception thrown parsing.", "valid...
Test Archive file is valid. Assumes the stream is at the start of the file. Be aware that this method makes a pass over the whole file. @return True if file can be successfully parsed.
[ "Test", "Archive", "file", "is", "valid", ".", "Assumes", "the", "stream", "is", "at", "the", "start", "of", "the", "file", ".", "Be", "aware", "that", "this", "method", "makes", "a", "pass", "over", "the", "whole", "file", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/ArchiveReader.java#L277-L288
36,696
iipc/webarchive-commons
src/main/java/org/archive/io/ArchiveReader.java
ArchiveReader.logStdErr
public void logStdErr(Level level, String message) { System.err.println(level.toString() + " " + message); }
java
public void logStdErr(Level level, String message) { System.err.println(level.toString() + " " + message); }
[ "public", "void", "logStdErr", "(", "Level", "level", ",", "String", "message", ")", "{", "System", ".", "err", ".", "println", "(", "level", ".", "toString", "(", ")", "+", "\" \"", "+", "message", ")", ";", "}" ]
Log on stderr. Logging should go via the logging system. This method bypasses the logging system going direct to stderr. Should not generally be used. Its used for rare messages that come of cmdline usage of ARCReader ERRORs and WARNINGs. Override if using ARCReader in a context where no stderr or where you'd like to redirect stderr to other than System.err. @param level Level to log message at. @param message Message to log.
[ "Log", "on", "stderr", ".", "Logging", "should", "go", "via", "the", "logging", "system", ".", "This", "method", "bypasses", "the", "logging", "system", "going", "direct", "to", "stderr", ".", "Should", "not", "generally", "be", "used", ".", "Its", "used",...
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/ArchiveReader.java#L389-L391
36,697
iipc/webarchive-commons
src/main/java/org/archive/format/gzip/GZIPDecoder.java
GZIPDecoder.alignOnMagic3
public long alignOnMagic3(InputStream is) throws IOException { long bytesSkipped = 0; byte lookahead[] = new byte[3]; int keep = 0; while(true) { if(keep == 2) { lookahead[0] = lookahead[1]; lookahead[1] = lookahead[2]; } else if(keep == 1) { lookahead[0] = lookahead[2]; } int amt = is.read(lookahead, keep, 3 - keep); if(amt == -1) { long skippedBeforeEOF = bytesSkipped + keep; if(skippedBeforeEOF == 0) { return SEARCH_EOF_AT_START; } return -1 * skippedBeforeEOF; } // TODO: handle read < # of bytes wanted... // we have 3 bytes, can it be a gzipmember? // Legend: // ? = uninspected byte // 1 = gzip magic 1 // 2 = gzip magic 2 // ! = wrong byte value // ??? if(lookahead[0] != GZIP_MAGIC_ONE) { // !?? // nope. are the next 2 possibilities? if((lookahead[1] == GZIP_MAGIC_ONE) && (lookahead[2] == GZIP_MAGIC_TWO)) { // !12 keep = 2; } else if(lookahead[2] == GZIP_MAGIC_ONE) { // !!1 keep = 1; } else { // !!! keep = 0; } bytesSkipped += (3-keep); continue; } // 1?? if((lookahead[1] & 0xff) != GZIP_MAGIC_TWO) { // 1!? // nope. is the last a possible start? if(lookahead[2] == GZIP_MAGIC_ONE) { // 1!1 keep = 1; } else { // 1!! // just keep lookin, no backtrack keep = 0; } bytesSkipped += (3-keep); continue; } // 12? if(!GZIPHeader.isValidCompressionMethod(lookahead[2])) { if(lookahead[2] == GZIP_MAGIC_ONE) { // 121 keep = 1; } else { // 12! // just keep lookin, no backtrack } bytesSkipped += (3-keep); continue; } // found it! return bytesSkipped; } }
java
public long alignOnMagic3(InputStream is) throws IOException { long bytesSkipped = 0; byte lookahead[] = new byte[3]; int keep = 0; while(true) { if(keep == 2) { lookahead[0] = lookahead[1]; lookahead[1] = lookahead[2]; } else if(keep == 1) { lookahead[0] = lookahead[2]; } int amt = is.read(lookahead, keep, 3 - keep); if(amt == -1) { long skippedBeforeEOF = bytesSkipped + keep; if(skippedBeforeEOF == 0) { return SEARCH_EOF_AT_START; } return -1 * skippedBeforeEOF; } // TODO: handle read < # of bytes wanted... // we have 3 bytes, can it be a gzipmember? // Legend: // ? = uninspected byte // 1 = gzip magic 1 // 2 = gzip magic 2 // ! = wrong byte value // ??? if(lookahead[0] != GZIP_MAGIC_ONE) { // !?? // nope. are the next 2 possibilities? if((lookahead[1] == GZIP_MAGIC_ONE) && (lookahead[2] == GZIP_MAGIC_TWO)) { // !12 keep = 2; } else if(lookahead[2] == GZIP_MAGIC_ONE) { // !!1 keep = 1; } else { // !!! keep = 0; } bytesSkipped += (3-keep); continue; } // 1?? if((lookahead[1] & 0xff) != GZIP_MAGIC_TWO) { // 1!? // nope. is the last a possible start? if(lookahead[2] == GZIP_MAGIC_ONE) { // 1!1 keep = 1; } else { // 1!! // just keep lookin, no backtrack keep = 0; } bytesSkipped += (3-keep); continue; } // 12? if(!GZIPHeader.isValidCompressionMethod(lookahead[2])) { if(lookahead[2] == GZIP_MAGIC_ONE) { // 121 keep = 1; } else { // 12! // just keep lookin, no backtrack } bytesSkipped += (3-keep); continue; } // found it! return bytesSkipped; } }
[ "public", "long", "alignOnMagic3", "(", "InputStream", "is", ")", "throws", "IOException", "{", "long", "bytesSkipped", "=", "0", ";", "byte", "lookahead", "[", "]", "=", "new", "byte", "[", "3", "]", ";", "int", "keep", "=", "0", ";", "while", "(", ...
Read bytes from InputStream argument until 3 bytes are found that appear to be the start of a GZIPHeader. leave the stream on the 4th byte, and return the number of bytes skipped before finding the 3 bytes. @param is InputStream to read from @return number of bytes skipped before finding the gzip magic: 0 if the first 3 bytes matched. If no magic was found before an EOF, returns the -1 * the number of bytes skipped before hitting the EOF. As a special case, if the stream was at EOF when the method is called, returns GZIPHeaderParser.SEARCH_EOF_AT_START (which is Long.MIN_VALUE) @throws IOException
[ "Read", "bytes", "from", "InputStream", "argument", "until", "3", "bytes", "are", "found", "that", "appear", "to", "be", "the", "start", "of", "a", "GZIPHeader", ".", "leave", "the", "stream", "on", "the", "4th", "byte", "and", "return", "the", "number", ...
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/format/gzip/GZIPDecoder.java#L43-L122
36,698
iipc/webarchive-commons
src/main/java/org/archive/io/warc/WARCReader.java
WARCReader.output
protected static void output(WARCReader reader, String format) throws IOException, java.text.ParseException { if (!reader.output(format)) { throw new IOException("Unsupported format: " + format); } }
java
protected static void output(WARCReader reader, String format) throws IOException, java.text.ParseException { if (!reader.output(format)) { throw new IOException("Unsupported format: " + format); } }
[ "protected", "static", "void", "output", "(", "WARCReader", "reader", ",", "String", "format", ")", "throws", "IOException", ",", "java", ".", "text", ".", "ParseException", "{", "if", "(", "!", "reader", ".", "output", "(", "format", ")", ")", "{", "thr...
Write out the arcfile. @param reader @param format Format to use outputting. @throws IOException @throws java.text.ParseException
[ "Write", "out", "the", "arcfile", "." ]
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/warc/WARCReader.java#L151-L156
36,699
iipc/webarchive-commons
src/main/java/org/archive/util/iterator/RegexLineIterator.java
RegexLineIterator.transform
protected String transform(String line) { ignoreLine.reset(line); if(ignoreLine.matches()) { return null; } extractLine.reset(line); if(extractLine.matches()) { StringBuffer output = new StringBuffer(); // TODO: consider if a loop that find()s all is more // generally useful here extractLine.appendReplacement(output,outputTemplate); return output.toString(); } // no match; possibly error logger.warning("line not extracted nor no-op: "+line); return null; }
java
protected String transform(String line) { ignoreLine.reset(line); if(ignoreLine.matches()) { return null; } extractLine.reset(line); if(extractLine.matches()) { StringBuffer output = new StringBuffer(); // TODO: consider if a loop that find()s all is more // generally useful here extractLine.appendReplacement(output,outputTemplate); return output.toString(); } // no match; possibly error logger.warning("line not extracted nor no-op: "+line); return null; }
[ "protected", "String", "transform", "(", "String", "line", ")", "{", "ignoreLine", ".", "reset", "(", "line", ")", ";", "if", "(", "ignoreLine", ".", "matches", "(", ")", ")", "{", "return", "null", ";", "}", "extractLine", ".", "reset", "(", "line", ...
Loads next item into lookahead spot, if available. Skips lines matching ignoreLine; extracts desired portion of lines matching extractLine; informationally reports any lines matching neither. @return whether any item was loaded into next field
[ "Loads", "next", "item", "into", "lookahead", "spot", "if", "available", ".", "Skips", "lines", "matching", "ignoreLine", ";", "extracts", "desired", "portion", "of", "lines", "matching", "extractLine", ";", "informationally", "reports", "any", "lines", "matching"...
988bec707c27a01333becfc3bd502af4441ea1e1
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/iterator/RegexLineIterator.java#L74-L90