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 ( ) ...
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 . star...
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 ( ...
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 , ...
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 . sk...
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...
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 ...
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 ...
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 "...
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 ( ) ; StreamG...
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 ( ) - startT...
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 ....
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 ) in...
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 + ...
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 ( ...
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 , RegexLi...
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 ) ...
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 ....
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 ...
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 ...
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...
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 uncompressedC...
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 ...
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 . getAbsolutePa...
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 ....
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 ) ; } e...
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...
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 ( ! ...
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 ...
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 contentTy...
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 RecoverableIOExceptio...
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 ,...
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 ...
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 = l...
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 ( ve...
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 =...
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 = ...
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...
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 a...
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 . toStri...
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 ) ) ; re...
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 .