idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
8,800
public void setValueTypes ( List < ValueType < ? > > valueTypes ) { Validate . noNullElements ( valueTypes ) ; this . sqlExecutor . setValueTypes ( valueTypes ) ; this . callExecutor . setValueTypes ( valueTypes ) ; }
Sets the value types .
8,801
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 ) ; }
Returns the SQL which located within a package specified by the packageName as dialectname_version . sql or version . sql .
8,802
protected boolean existsTable ( ) { try { int count = sqlManager . getSingleResult ( Integer . class , new StringSqlResource ( String . format ( "SELECT COUNT(*) FROM %s" , tableName ) ) ) ; if ( count == 0 ) { return false ; } return true ; } catch ( SQLRuntimeException ex ) { return false ; } }
Checks the table which manages a schema version exists or not exists .
8,803
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 ) ) ) ; }
Creates table which manages schema version and insert an initial record as version 0 .
8,804
public synchronized static Session getSession ( ) { if ( session == null ) { Properties properties = IOUtil . loadProperties ( "jdbc.properties" ) ; session = getSession ( properties ) ; } return session ; }
Returns a session configured with the properties specified in the jdbc . properties file .
8,805
public static boolean isUncountable ( String word ) { for ( String w : UNCOUNTABLE ) { if ( w . equalsIgnoreCase ( word ) ) { return true ; } } return false ; }
Return true if the word is uncountable .
8,806
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 ; }
Return the singularized version of a word .
8,807
public boolean match ( String word ) { int flags = 0 ; if ( ignoreCase ) { flags = flags | Pattern . CASE_INSENSITIVE ; } return Pattern . compile ( pattern , flags ) . matcher ( word ) . find ( ) ; }
Does the given word match?
8,808
public String replace ( String word ) { int flags = 0 ; if ( ignoreCase ) { flags = flags | Pattern . CASE_INSENSITIVE ; } return Pattern . compile ( pattern , flags ) . matcher ( word ) . replaceAll ( replacement ) ; }
Replace the word with its pattern .
8,809
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 ( ) ; }
Selects the Database Dialect based on the JDBC connection URL .
8,810
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 ; }
Parse the comment .
8,811
@ SuppressWarnings ( "unchecked" ) public BeanDesc getBeanDesc ( Object obj ) { if ( obj instanceof Map ) { return new MapBeanDescImpl ( ( Map < String , Object > ) obj ) ; } else { return getBeanDesc ( obj . getClass ( ) ) ; } }
Constructs a bean descriptor out of an Object instance .
8,812
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 ; }
Constructs a bean descriptor out of a class .
8,813
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 ) ) ; } }
Parse the SQL .
8,814
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 + "*/" ) ) ; } }
Parse an SQL comment .
8,815
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 ( ) ; }
Parse an IF node .
8,816
protected void parseBegin ( ) { BeginNode beginNode = new BeginNode ( ) ; peek ( ) . addChild ( beginNode ) ; push ( beginNode ) ; parseEnd ( ) ; }
Parse a BEGIN node .
8,817
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 ( ) ) ) ; }
Parse an END node .
8,818
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 ( ) ; }
Parse an ELSE node .
8,819
protected void parseBindVariable ( ) { String expr = tokenizer . getToken ( ) ; peek ( ) . addChild ( new BindVariableNode ( expr , beanDescFactory ) ) ; }
Parse the bind variable .
8,820
protected synchronized WriterPoolMember makeNewWriterIfAppropriate ( ) { long now = System . currentTimeMillis ( ) ; lastWriterNeededTime = now ; if ( currentActive < maxActive ) { currentActive ++ ; lastWriterRolloverTime = now ; return makeWriter ( ) ; } return null ; }
Create a new writer instance if still below maxActive count . Remember times to help make later decision when writer should be discarded .
8,821
public synchronized void invalidateFile ( WriterPoolMember f ) throws IOException { try { destroyWriter ( f ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) ) ; } File file = f . getFile ( ) ; file . renameTo ( new File ( file . getAbsoluteFile ( ) + WriterPoolMember . INVALID_SUFFIX ) ) ; }
Close and discard a writer that experienced a potentially - corrupting error .
8,822
public void skipHttpHeader ( ) throws IOException { if ( this . contentHeaderStream == null ) { return ; } for ( int available = this . contentHeaderStream . available ( ) ; this . contentHeaderStream != null && ( available = this . contentHeaderStream . available ( ) ) > 0 ; ) { byte [ ] buffer = new byte [ available ] ; read ( buffer , 0 , available ) ; } }
Skip over the the content headers if present .
8,823
private InputStream readContentHeaders ( ) throws IOException { 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" ) ; } 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 ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( statusBytes . length + 4 * 1024 ) ; baos . write ( statusBytes ) ; 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 ) ) ; } baos . write ( lineBytes ) ; if ( ( lineBytes . length - eolCharCount ) <= 0 ) { break ; } } byte [ ] headerBytes = baos . toByteArray ( ) ; this . contentHeadersLength = headerBytes . length ; ByteArrayInputStream bais = new ByteArrayInputStream ( headerBytes ) ; if ( ! bais . markSupported ( ) ) { throw new IOException ( "ByteArrayInputStream does not support mark" ) ; } bais . mark ( headerBytes . length ) ; bais . read ( statusBytes , 0 , statusBytes . length ) ; this . contentHeaders = LaxHttpParser . parseHeaders ( bais , ARCConstants . DEFAULT_ENCODING ) ; bais . reset ( ) ; return bais ; }
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 .
8,824
public static ProcessUtils . ProcessResult exec ( String [ ] args ) throws IOException { Process p = Runtime . getRuntime ( ) . exec ( args ) ; ProcessUtils pu = new ProcessUtils ( ) ; 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 ; }
Runs process .
8,825
public void open ( OutputStream wrappedStream ) throws IOException { if ( isOpen ( ) ) { throw new IOException ( "ROS already open for " + Thread . currentThread ( ) . getName ( ) ) ; } clearForReuse ( ) ; this . out = wrappedStream ; startTime = System . currentTimeMillis ( ) ; }
Wrap the given stream both recording and passing along any data written to this RecordingOutputStream .
8,826
protected void checkLimits ( ) throws RecorderIOException { if ( messageBodyBeginMark < 0 ) { if ( position > MAX_HEADER_MATERIAL ) { throw new RecorderTooMuchHeaderException ( ) ; } } if ( position > maxLength ) { throw new RecorderLengthExceededException ( ) ; } long duration = System . currentTimeMillis ( ) - startTime ; duration = Math . max ( duration , 1 ) ; if ( duration > timeoutMs ) { throw new RecorderTimeoutException ( ) ; } 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 ) ; } } }
Check any enforced limits .
8,827
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 ++ ; }
Record the given byte for later recovery
8,828
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 ) ; }
Record the given byte - array range for recovery later
8,829
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 ; if ( toCopy < len ) { tailRecord ( b , off + toCopy , len - toCopy ) ; } } }
Record without digesting .
8,830
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 ; }
Set limits on length time and rate to enforce .
8,831
public void resetLimits ( ) { maxLength = Long . MAX_VALUE ; timeoutMs = Long . MAX_VALUE ; maxRateBytesPerMs = Long . MAX_VALUE ; }
Reset limits to effectively - unlimited defaults
8,832
protected static InputStream countingStream ( InputStream in , int lookback ) throws IOException { CountingInputStream cin = new CountingInputStream ( in ) ; cin . mark ( lookback ) ; return cin ; }
A CountingInputStream is inserted to read compressed - offsets .
8,833
public char charAt ( int index ) { if ( index < 0 || index >= this . length ( ) ) { throw new IndexOutOfBoundsException ( "index=" + index + " - should be between 0 and length()=" + this . length ( ) ) ; } if ( index < prefixBuffer . limit ( ) ) { return prefixBuffer . get ( index ) ; } long charFileIndex = ( long ) index - ( long ) prefixBuffer . limit ( ) ; long charFileLength = ( long ) this . length ( ) - ( long ) prefixBuffer . limit ( ) ; 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 ( ) ) { 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 ) ) ) ; }
Get character at passed absolute position .
8,834
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 ) { int c = ( ( u << 4 ) + l ) ; buffer . write ( ( char ) c ) ; i += 2 ; continue ; } } } buffer . write ( b ) ; } return buffer . toByteArray ( ) ; }
Decodes an array of URL safe 7 - bit characters into an array of original bytes . Escaped characters are converted back to their original representation .
8,835
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 ) ; }
Encodes a string into its URL safe form using the specified string charset . Unsafe characters are escaped .
8,836
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 ( ) ) ; } }
Read a set of SURT prefixes from a reader source ; keep sorted and with redundant entries removed .
8,837
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 ) { addFromPlain ( s ) ; } } } }
Import SURT prefixes from a reader with mixed URI and SURT prefix format .
8,838
public static String fromURI ( String s , boolean preserveCase ) { Matcher m = TextUtils . getMatcher ( URI_SPLITTER , s ) ; if ( ! m . matches ( ) ) { TextUtils . recycleMatcher ( m ) ; return s ; } StringBuffer builder = new StringBuffer ( s . length ( ) + 3 ) ; append ( builder , s , m . start ( 1 ) , m . end ( 1 ) ) ; builder . append ( BEGIN_TRANSFORMED_AUTHORITY ) ; if ( m . start ( 4 ) > - 1 ) { append ( builder , s , m . start ( 4 ) , m . end ( 4 ) ) ; } else { 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 ) ; builder . append ( TRANSFORMED_HOST_DELIM ) ; hostSegEnd = i - 1 ; } } append ( builder , s , m . start ( 6 ) , m . end ( 6 ) ) ; append ( builder , s , m . start ( 3 ) , m . end ( 3 ) ) ; append ( builder , s , m . start ( 2 ) , m . end ( 2 ) ) ; builder . append ( END_TRANSFORMED_AUTHORITY ) ; append ( builder , s , m . start ( 7 ) , m . end ( 7 ) ) ; if ( ! preserveCase ) { for ( int i = 0 ; i < builder . length ( ) ; i ++ ) { builder . setCharAt ( i , Character . toLowerCase ( builder . charAt ( ( i ) ) ) ) ; } } TextUtils . recycleMatcher ( m ) ; return builder . toString ( ) ; }
Utility method for creating the SURT form of the URI in the given String .
8,839
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 ( ) ; 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 ( ) ; } }
Main dumps rsync file to STDOUT .
8,840
public void position ( long p ) throws IOException { if ( ( p < 0 ) || ( p > array . length ) ) { throw new IOException ( "Invalid position: " + p ) ; } offset = ( int ) p ; }
Repositions the stream .
8,841
public int getFieldIndex ( String name ) { Integer val = this . nameToIndex . get ( name ) ; if ( val == null ) { return - 1 ; } return val ; }
Return field index for given name
8,842
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 ] ; for ( int i = 0 ; i < readyToUse . length ; i ++ ) { readyToUse [ i ] = true ; } return new ByteBufferInputStream ( byteBuffer , size , 0 , readyToUse ) ; }
Creates a new byte - buffer input stream by mapping a given file channel .
8,843
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 ( ) ; }
Convert milliseconds value to a human - readable duration of mixed units using units no larger than days . For example 5d12h13m12s113ms or 19h51m .
8,844
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 ; }
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 .
8,845
protected boolean lookahead ( ) { try { next = this . reader . readLine ( ) ; if ( next == null ) { reader . close ( ) ; } return ( next != null ) ; } catch ( IOException e ) { logger . warning ( e . toString ( ) ) ; return false ; } }
Loads next line into lookahead spot
8,846
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 ( ) ; } } }
Decode gzipped cdx to a temporary file
8,847
public String getField ( String name , String defaultVal ) { int index = getFieldIndex ( name ) ; return ( isInRange ( index ) ? this . fields . get ( index ) : defaultVal ) ; }
Return field for given name or defaultVal if not found
8,848
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 .
8,849
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 { return result ; } } FileInputStream fis = null ; FileOutputStream fos = null ; FileChannel fcin = null ; FileChannel fcout = null ; try { fis = new FileInputStream ( src ) ; fos = new FileOutputStream ( dest ) ; fcin = fis . getChannel ( ) ; fcout = fos . getChannel ( ) ; if ( extent < 0 ) { extent = fcin . size ( ) ; } long trans = fcin . transferTo ( 0 , extent , fcout ) ; if ( trans < extent ) { result = false ; } result = true ; } catch ( IOException e ) { 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 { if ( fcin != null ) { fcin . close ( ) ; } if ( fcout != null ) { fcout . close ( ) ; } if ( fis != null ) { fis . close ( ) ; } if ( fos != null ) { fos . close ( ) ; } } return result ; }
Copy up to extent bytes of the source file to the destination
8,850
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 ) ; }
Get a list of all files in directory that have passed prefix .
8,851
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 ; }
Test file exists and is readable .
8,852
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 ) ; } }
Load Properties instance from a File
8,853
public static void storeProperties ( Properties p , File file ) throws IOException { FileOutputStream fos = new FileOutputStream ( file ) ; try { p . store ( fos , "" ) ; } finally { ArchiveUtils . closeQuietly ( fos ) ; } }
Store Properties instance to a File
8,854
public static List < File > ensureWriteableDirectory ( List < File > dirs ) throws IOException { for ( Iterator < File > i = dirs . iterator ( ) ; i . hasNext ( ) ; ) { FileUtils . ensureWriteableDirectory ( i . next ( ) ) ; } return dirs ; }
Ensure writeable directories .
8,855
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 ; }
Ensure writeable directory .
8,856
public InputStream inputWrap ( InputStream is ) throws IOException { logger . fine ( Thread . currentThread ( ) . getName ( ) + " wrapping input" ) ; this . characterEncoding = null ; this . inputIsChunked = false ; this . contentEncoding = null ; this . ris . open ( is ) ; return this . ris ; }
Wrap the provided stream with the internal RecordingInputStream
8,857
public void close ( ) { logger . fine ( Thread . currentThread ( ) . getName ( ) + " closing" ) ; try { this . ris . close ( ) ; } catch ( IOException e ) { 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 ) ; } }
Close all streams .
8,858
public void closeRecorders ( ) { try { this . ris . closeRecorder ( ) ; this . ros . closeRecorder ( ) ; } catch ( IOException e ) { DevUtils . warnHandle ( e , "Convert to runtime exception?" ) ; } }
Close both input and output recorders .
8,859
private void delete ( String name ) { File f = new File ( name ) ; if ( f . exists ( ) ) { f . delete ( ) ; } }
Delete file if exists .
8,860
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 "" ; } }
Return a short prefix of the presumed - textual content as a String .
8,861
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 ) ) ; } InputStream is = rec . inputWrap ( new BufferedInputStream ( in ) ) ; final int BUFFER_SIZE = 1024 * 4 ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; while ( true ) { int x = is . read ( buffer ) ; if ( x == - 1 ) { break ; } } is . close ( ) ; return rec ; }
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 .
8,862
protected String createRecordHeader ( WARCRecordInfo metaRecord ) throws IllegalArgumentException { final StringBuilder sb = new StringBuilder ( 2048 ) ; sb . append ( WARC_ID ) . append ( CRLF ) ; sb . append ( HEADER_KEY_TYPE ) . append ( COLON_SPACE ) . append ( metaRecord . getType ( ) ) . append ( CRLF ) ; 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 ( ) ; }
final ANVLRecord xtraHeaders final long contentLength )
8,863
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 ; }
Get a matcher object for a precompiled regex pattern .
8,864
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 ; }
Utility method using a precompiled pattern instead of using the replaceAll method of the String class . This method will also be reusing Matcher objects .
8,865
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 ; }
Utility method using a precompiled pattern instead of using the matches method of the String class . This method will also be reusing Matcher objects .
8,866
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 ; }
Utility method using a precompiled pattern instead of using the split method of the String class .
8,867
public static CharSequence unescapeHtml ( final CharSequence cs ) { if ( cs == null ) { return cs ; } return StringEscapeUtils . unescapeHtml ( cs . toString ( ) ) ; }
Replaces HTML Entity Encodings .
8,868
@ SuppressWarnings ( "deprecation" ) public static String urlEscape ( String s ) { try { return URLEncoder . encode ( s , "UTF8" ) ; } catch ( UnsupportedEncodingException e ) { return URLEncoder . encode ( s ) ; } }
Exception - and warning - free URL - escaping utility method .
8,869
@ SuppressWarnings ( "deprecation" ) public static String urlUnescape ( String s ) { try { return URLDecoder . decode ( s , "UTF8" ) ; } catch ( UnsupportedEncodingException e ) { return URLDecoder . decode ( s ) ; } }
Exception - and warning - free URL - unescaping utility method .
8,870
public boolean containsPrefixOf ( String s ) { SortedSet < String > sub = headSet ( s ) ; if ( ! sub . isEmpty ( ) && s . startsWith ( ( String ) sub . last ( ) ) ) { return true ; } return contains ( s ) ; }
Test whether the given String is prefixed by one of this set s entries .
8,871
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 .
8,872
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 ; }
Truncate passed mimetype .
8,873
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 ) ; }
Reads the next little - endian unsigned 16 bit integer from the given stream .
8,874
public static int littleInt ( InputStream input ) throws IOException { char lo = littleChar ( input ) ; char hi = littleChar ( input ) ; return ( hi << 16 ) | lo ; }
Reads the next little - endian signed 32 - bit integer from the given stream .
8,875
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 ) ; }
Reads the next big - endian unsigned 16 bit integer from the given stream .
8,876
public static int bigInt ( InputStream input ) throws IOException { char hi = bigChar ( input ) ; char lo = bigChar ( input ) ; return ( hi << 16 ) | lo ; }
Reads the next big - endian signed 32 - bit integer from the given stream .
8,877
public void restoreFile ( File destination ) throws IOException { String nameAsStored = readUTF ( ) ; long lengthAtStoreTime = readLong ( ) ; File storedFile = new File ( getAuxiliaryDirectory ( ) , nameAsStored ) ; FileUtils . copyFile ( storedFile , destination , lengthAtStoreTime ) ; }
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 .
8,878
private int getTokenizedHeaderLine ( final InputStream stream , List < String > list ) throws IOException { 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 ) { continue ; } if ( list != null ) { list . add ( buffer . toString ( ) ) ; } break ; } else if ( c == HEADER_FIELD_SEPARATOR ) { if ( ! isStrict ( ) && previous == HEADER_FIELD_SEPARATOR ) { continue ; } if ( list != null ) { list . add ( buffer . toString ( ) ) ; } buffer . setLength ( 0 ) ; } else { buffer . append ( ( char ) c ) ; } } if ( list != null && ( list . size ( ) < 3 || list . size ( ) > 100 ) ) { throw new IOException ( "Unparseable header line: " + list ) ; } this . headerString = StringUtils . join ( list , " " ) ; return read ; }
Get a record header line as list of tokens .
8,879
public void skipHttpHeader ( ) throws IOException { if ( this . httpHeaderStream != null ) { for ( int available = this . httpHeaderStream . available ( ) ; this . httpHeaderStream != null && ( available = this . httpHeaderStream . available ( ) ) > 0 ; ) { byte [ ] buffer = new byte [ available ] ; read ( buffer , 0 , available ) ; } } }
Skip over the the http header if one present .
8,880
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 ; }
Check the generated UURI .
8,881
private String fixupAuthority ( String uriAuthority , String charset ) throws URIException { if ( uriAuthority != null ) { while ( uriAuthority . endsWith ( ESCAPED_SPACE ) ) { uriAuthority = uriAuthority . substring ( 0 , uriAuthority . length ( ) - 3 ) ; } int atIndex = uriAuthority . indexOf ( COMMERCIAL_AT ) ; int portColonIndex = uriAuthority . indexOf ( COLON , ( atIndex < 0 ) ? 0 : atIndex ) ; if ( atIndex < 0 && portColonIndex < 0 ) { return fixupDomainlabel ( uriAuthority ) ; } else if ( atIndex < 0 && portColonIndex > - 1 ) { String domain = fixupDomainlabel ( uriAuthority . substring ( 0 , portColonIndex ) ) ; String port = uriAuthority . substring ( portColonIndex ) ; return domain + port ; } else if ( atIndex > - 1 && portColonIndex < 0 ) { String userinfo = ensureMinimalEscaping ( uriAuthority . substring ( 0 , atIndex + 1 ) , charset ) ; String domain = fixupDomainlabel ( uriAuthority . substring ( atIndex + 1 ) ) ; return userinfo + domain ; } else { 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 ; }
Fixup authority portion of URI by removing any stray encoded spaces lowercasing any domain names and applying IDN - punycoding to Unicode domains .
8,882
private String fixupDomainlabel ( String label ) throws URIException { try { label = IDNA . toASCII ( label ) ; } catch ( IDNAException e ) { if ( TextUtils . matches ( ACCEPTABLE_ASCII_DOMAIN , label ) ) { } else { URIException ue = new URIException ( e + " " + label ) ; ue . initCause ( e ) ; throw ue ; } } label = label . toLowerCase ( ) ; return label ; }
Fixup the domain label part of the authority .
8,883
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 ) { throw e ; } IOException newE = new IOException ( e . getMessage ( ) + " (Offset " + offset + ")." ) ; newE . setStackTrace ( e . getStackTrace ( ) ) ; throw newE ; } return ( ARCRecord ) getCurrentRecord ( ) ; }
Create new arc record .
8,884
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 ) ; } } }
utility function for dumping prefix tree structure . intended for debug use .
8,885
public static String reduceSurtToAssignmentLevel ( String surt ) { Matcher matcher = TextUtils . getMatcher ( getTopmostAssignedSurtPrefixRegex ( ) , surt ) ; if ( matcher . find ( ) ) { surt = matcher . group ( ) ; } TextUtils . recycleMatcher ( matcher ) ; return surt ; }
Truncate SURT to its topmost assigned domain segment ; that is the public suffix plus one segment but as a SURT - ordered prefix .
8,886
private void buffer ( ) throws IOException { int remaining = buffer . length ; while ( remaining > 0 ) { int r = input . read ( buffer , buffer . length - remaining , remaining ) ; if ( r <= 0 ) { offset = 0 ; maxOffset = buffer . length - remaining ; return ; } remaining -= r ; } maxOffset = buffer . length ; offset = 0 ; }
Fills the buffer .
8,887
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 ) ) { long adj = p - blockStart ; offset = ( int ) adj ; return ; } positionDirect ( p ) ; }
Seeks to the given position . This method avoids re - filling the buffer if at all possible .
8,888
private void positionDirect ( long p ) throws IOException { long newBlockStart = p / buffer . length * buffer . length ; input . position ( newBlockStart ) ; buffer ( ) ; offset = ( int ) ( p % buffer . length ) ; }
Positions the underlying stream at the given position then refills the buffer .
8,889
protected InputStream getInputStream ( final File f , final long offset ) throws IOException { FileInputStream fin = new FileInputStream ( f ) ; return new BufferedInputStream ( fin ) ; }
Convenience method for constructors .
8,890
protected void cleanupCurrentRecord ( ) throws IOException { if ( this . currentRecord != null ) { this . currentRecord . close ( ) ; gotoEOR ( this . currentRecord ) ; this . currentRecord = null ; } }
Cleanout the current record if there is one .
8,891
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 ; }
Validate the Archive file .
8,892
public boolean isValid ( ) { boolean valid = false ; try { validate ( ) ; valid = true ; } catch ( Exception e ) { valid = false ; } return 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 .
8,893
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 .
8,894
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 ; } if ( lookahead [ 0 ] != GZIP_MAGIC_ONE ) { if ( ( lookahead [ 1 ] == GZIP_MAGIC_ONE ) && ( lookahead [ 2 ] == GZIP_MAGIC_TWO ) ) { keep = 2 ; } else if ( lookahead [ 2 ] == GZIP_MAGIC_ONE ) { keep = 1 ; } else { keep = 0 ; } bytesSkipped += ( 3 - keep ) ; continue ; } if ( ( lookahead [ 1 ] & 0xff ) != GZIP_MAGIC_TWO ) { if ( lookahead [ 2 ] == GZIP_MAGIC_ONE ) { keep = 1 ; } else { keep = 0 ; } bytesSkipped += ( 3 - keep ) ; continue ; } if ( ! GZIPHeader . isValidCompressionMethod ( lookahead [ 2 ] ) ) { if ( lookahead [ 2 ] == GZIP_MAGIC_ONE ) { keep = 1 ; } else { } bytesSkipped += ( 3 - keep ) ; continue ; } return bytesSkipped ; } }
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 .
8,895
protected static void output ( WARCReader reader , String format ) throws IOException , java . text . ParseException { if ( ! reader . output ( format ) ) { throw new IOException ( "Unsupported format: " + format ) ; } }
Write out the arcfile .
8,896
protected String transform ( String line ) { ignoreLine . reset ( line ) ; if ( ignoreLine . matches ( ) ) { return null ; } extractLine . reset ( line ) ; if ( extractLine . matches ( ) ) { StringBuffer output = new StringBuffer ( ) ; extractLine . appendReplacement ( output , outputTemplate ) ; return output . toString ( ) ; } logger . warning ( "line not extracted nor no-op: " + line ) ; return null ; }
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 .
8,897
protected static String decode ( String component , String charset ) throws URIException { if ( component == null ) { throw new IllegalArgumentException ( "Component array of chars may not be null" ) ; } byte [ ] rawdata = null ; rawdata = LaxURLCodec . decodeUrlLoose ( EncodingUtil . getAsciiBytes ( component ) ) ; return EncodingUtil . getString ( rawdata , charset ) ; }
overridden to use IA s LaxURLCodec which never throws DecoderException
8,898
protected void parseAuthority ( String original , boolean escaped ) throws URIException { super . parseAuthority ( original , escaped ) ; if ( _host != null && _authority != null && _host . length == _authority . length ) { _host = _authority ; } }
Coalesce the _host and _authority fields where possible .
8,899
protected void setURI ( ) { if ( _scheme != null ) { if ( _scheme . length == 4 && Arrays . equals ( _scheme , HTTP_SCHEME ) ) { _scheme = HTTP_SCHEME ; } else if ( _scheme . length == 5 && Arrays . equals ( _scheme , HTTPS_SCHEME ) ) { _scheme = HTTPS_SCHEME ; } } super . setURI ( ) ; }
Coalesce _scheme to existing instances where appropriate .