idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
4,200
|
private void replace ( final char [ ] revA , final char [ ] revB , final DiffBlock curA , final DiffBlock curB ) throws UnsupportedEncodingException { String text = copy ( revB , curB . getRevBStart ( ) , curB . getRevBEnd ( ) ) ; DiffPart action = new DiffPart ( DiffAction . REPLACE ) ; action . setStart ( version . length ( ) ) ; codecData . checkBlocksizeS ( version . length ( ) ) ; action . setLength ( curA . getRevAEnd ( ) - curA . getRevAStart ( ) ) ; codecData . checkBlocksizeE ( action . getLength ( ) ) ; action . setText ( text ) ; codecData . checkBlocksizeL ( text . getBytes ( WIKIPEDIA_ENCODING ) . length ) ; diff . add ( action ) ; version . append ( text ) ; }
|
Creates a replace operation .
|
4,201
|
private void cut ( final char [ ] revA , final DiffBlock curA ) { String text = copy ( revA , curA . getRevAStart ( ) , curA . getRevAEnd ( ) ) ; DiffPart action = new DiffPart ( DiffAction . CUT ) ; action . setStart ( version . length ( ) ) ; codecData . checkBlocksizeS ( version . length ( ) ) ; action . setLength ( curA . getRevAEnd ( ) - curA . getRevAStart ( ) ) ; codecData . checkBlocksizeE ( action . getLength ( ) ) ; action . setText ( Integer . toString ( curA . getId ( ) ) ) ; codecData . checkBlocksizeB ( curA . getId ( ) ) ; diff . add ( action ) ; bufferMap . put ( curA . getId ( ) , text ) ; }
|
Creates a cut operation .
|
4,202
|
private void paste ( final DiffBlock curB ) { String text = bufferMap . remove ( curB . getId ( ) ) ; DiffPart action = new DiffPart ( DiffAction . PASTE ) ; action . setStart ( version . length ( ) ) ; codecData . checkBlocksizeS ( version . length ( ) ) ; action . setText ( Integer . toString ( curB . getId ( ) ) ) ; codecData . checkBlocksizeB ( curB . getId ( ) ) ; diff . add ( action ) ; version . append ( text ) ; }
|
Creates a paste operation .
|
4,203
|
private synchronized void log ( final String text ) { try { this . writer . write ( text ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } }
|
Writes the given text to the output file .
|
4,204
|
public void logError ( final Level level , final String message , final Error e ) { try { Logger errors = LoggingFactory . getLogger ( LoggingFactory . NAME_ERROR_LOGGER ) ; errors . logThrowable ( level , message , e ) ; } catch ( LoggingException ex ) { ex . printStackTrace ( ) ; } if ( logLevel . toInt ( ) > level . toInt ( ) ) { return ; } logThrowable ( level , message , e ) ; }
|
The occurred error with the related log level and message has to be given to this method .
|
4,205
|
public synchronized void logMessage ( final Level level , final String message ) { if ( logLevel . toInt ( ) > level . toInt ( ) ) { return ; } try { this . writer . write ( System . currentTimeMillis ( ) + "\t" + consumerName + " [" + type . toString ( ) + "] " + "\t" + message + "\r\n" ) ; this . writer . flush ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } }
|
This method will be called with a message and the related log level . It be verified if the message should be logged or not .
|
4,206
|
private synchronized void logThrowable ( final Level level , final String message , final Throwable t ) { if ( t != null ) { log ( "\r\n[" + System . currentTimeMillis ( ) + "]\t" + message ) ; log ( "\r\n" + t ) ; log ( "\r\n" ) ; for ( StackTraceElement st : t . getStackTrace ( ) ) { log ( "\t" + st . toString ( ) + "\r\n" ) ; } Throwable c = t . getCause ( ) ; if ( c != null ) { log ( "Caused by:\t" + c + "\r\n" ) ; for ( StackTraceElement st : c . getStackTrace ( ) ) { log ( "\t" + st . toString ( ) + "\r\n" ) ; } } log ( "\r\n" ) ; this . flush ( ) ; } }
|
The occurred error or exception with the related log level and message will be logged by this method .
|
4,207
|
public static String sqlEscape ( String str ) { final int len = str . length ( ) ; buffer . setLength ( 0 ) ; StringBuilder sql = buffer ; for ( int i = 0 ; i < len ; i ++ ) { char c = str . charAt ( i ) ; switch ( c ) { case '\u0000' : sql . append ( '\\' ) . append ( '0' ) ; break ; case '\n' : sql . append ( '\\' ) . append ( 'n' ) ; break ; case '\t' : sql . append ( '\\' ) . append ( 't' ) ; break ; case '\r' : sql . append ( '\\' ) . append ( 'r' ) ; break ; case '\u001a' : sql . append ( '\\' ) . append ( 'Z' ) ; break ; case '\'' : sql . append ( '\\' ) . append ( '\'' ) ; break ; case '\"' : sql . append ( '\\' ) . append ( '"' ) ; break ; case '\b' : sql . append ( '\\' ) . append ( 'b' ) ; break ; case '\\' : sql . append ( '\\' ) . append ( '\\' ) ; break ; default : sql . append ( c ) ; break ; } } return sql . toString ( ) ; }
|
Replaces all problematic characters from a String with their escaped versions to make it SQL conform .
|
4,208
|
public static List < String > getTemplateNames ( String text , String title ) throws LinkTargetException , EngineException , FileNotFoundException , JAXBException { return ( List < String > ) parsePage ( new TemplateNameExtractor ( ) , text , title , - 1 ) ; }
|
Extracts template names from Wikitext by descending into every node and looking for templates . Results may contain duplicates if template appears multiple times in the article .
|
4,209
|
private static Object parsePage ( AstVisitor v , String text , String title , long revision ) throws LinkTargetException , EngineException , FileNotFoundException , JAXBException { return v . go ( getCompiledPage ( text , title , revision ) . getPage ( ) ) ; }
|
Parses the page with the Sweble parser using a SimpleWikiConfiguration and the provided visitor .
|
4,210
|
private static String getTemplateMarker ( String str ) throws IllegalStateException { Pattern p = Pattern . compile ( "\\{\\{(.*?)\\}\\}" , Pattern . DOTALL ) ; Matcher matcher = p . matcher ( str ) ; String tpl = null ; while ( matcher . find ( ) ) { if ( tpl != null ) { throw new IllegalStateException ( "More than one template in the sentence." ) ; } tpl = matcher . group ( 1 ) ; } return tpl ; }
|
Returns the template marker of the sentence .
|
4,211
|
public void process ( final Task < Diff > task ) throws ConfigurationException , IOException , SQLConsumerException { long startTime = System . currentTimeMillis ( ) ; TaskTypes type = task . getTaskType ( ) ; if ( type == TaskTypes . TASK_FULL || type == TaskTypes . TASK_PARTIAL_FIRST ) { this . sqlEncoder . init ( ) ; this . processingTimeSQL = 0 ; } super . process ( task ) ; this . processingTimeSQL += System . currentTimeMillis ( ) - startTime ; if ( type == TaskTypes . TASK_FULL || type == TaskTypes . TASK_PARTIAL_LAST ) { ArticleInformation info = task . getHeader ( ) ; info . setEncodedSize ( this . sqlEncoder . getEncodedSize ( ) ) ; info . setEncodedSQLSize ( this . sqlEncoder . getEncodedSQLSize ( ) ) ; info . setExitingTime ( System . currentTimeMillis ( ) ) ; info . setProcessingTimeSQL ( processingTimeSQL ) ; String succesReport = info . toString ( ) ; this . outputLogger . logMessage ( Level . INFO , "\r\n" + succesReport ) ; } }
|
This method will process the given DiffTask and send him to the specified output .
|
4,212
|
public void add ( final D data ) { this . container . add ( data ) ; if ( data instanceof ISizeable ) { this . byteSize += ( ( ISizeable ) data ) . byteSize ( ) ; } }
|
Adds data to this task .
|
4,213
|
public void generate ( ) throws WikiApiException { Indexer data = null ; try { data = new Indexer ( config ) ; System . out . println ( "GENERATING INDEX STARTED" ) ; long bufferSize = config . getBufferSize ( ) ; Revision rev ; long count = 0 ; long last = 0 , now , start = System . currentTimeMillis ( ) ; Iterator < Revision > it = new IndexIterator ( config ) ; while ( it . hasNext ( ) ) { if ( ++ count % bufferSize == 0 ) { now = System . currentTimeMillis ( ) - start ; System . out . println ( Time . toClock ( now ) + "\t" + ( now - last ) + "\tINDEXING " + count ) ; last = now ; } rev = it . next ( ) ; data . index ( rev ) ; } System . out . println ( "GENERATING INDEX ENDED + (" + Time . toClock ( System . currentTimeMillis ( ) - start ) + ")" ) ; } catch ( Exception e ) { throw new WikiApiException ( e ) ; } finally { if ( data != null ) { data . close ( ) ; } } }
|
Starts the generation of the indices .
|
4,214
|
private static Properties load ( String configFilePath ) { Properties props = new Properties ( ) ; BufferedInputStream fis = null ; try { File configFile = new File ( configFilePath ) ; fis = new BufferedInputStream ( new FileInputStream ( configFile ) ) ; props . load ( fis ) ; } catch ( IOException e ) { System . err . println ( "Could not load configuration file " + configFilePath ) ; } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException e ) { System . err . println ( "Error closing file stream of configuration file " + configFilePath ) ; } } } return props ; }
|
Load a properties file from the classpath
|
4,215
|
public List < TextPair > getInlineTextPairs ( boolean markTemplates ) { List < TextPair > pairList = new ArrayList < TextPair > ( ) ; try { List < ExtractedSection > beforeSections = null ; List < ExtractedSection > afterSections = null ; if ( markTemplates ) { beforeSections = ParseUtils . getSections ( before . getRevisionText ( ) , before . getRevisionID ( ) + "" , before . getRevisionID ( ) , Arrays . asList ( new String [ ] { template } ) ) ; afterSections = ParseUtils . getSections ( after . getRevisionText ( ) , after . getRevisionID ( ) + "" , after . getRevisionID ( ) , Arrays . asList ( new String [ ] { template } ) ) ; } else { beforeSections = ParseUtils . getSections ( before . getRevisionText ( ) , before . getRevisionID ( ) + "" , before . getRevisionID ( ) ) ; afterSections = ParseUtils . getSections ( after . getRevisionText ( ) , after . getRevisionID ( ) + "" , after . getRevisionID ( ) ) ; } for ( ExtractedSection tplSect : revPairType == RevisionPairType . deleteTemplate ? beforeSections : afterSections ) { if ( containsIgnoreCase ( tplSect . getTemplates ( ) , template ) ) { for ( ExtractedSection nonTplSect : revPairType == RevisionPairType . deleteTemplate ? afterSections : beforeSections ) { if ( tplSect . getTitle ( ) != null && nonTplSect . getTitle ( ) != null && tplSect . getTitle ( ) . equalsIgnoreCase ( nonTplSect . getTitle ( ) ) ) { if ( revPairType == RevisionPairType . deleteTemplate ) { pairList . add ( new TextPair ( tplSect . getBody ( ) , nonTplSect . getBody ( ) ) ) ; } else { pairList . add ( new TextPair ( nonTplSect . getBody ( ) , tplSect . getBody ( ) ) ) ; } } } } } } catch ( Exception ex ) { System . err . println ( ex . getMessage ( ) ) ; } return pairList ; }
|
Returns the text around the given template and returns the corresponding text in the other pair part of the RevisionPair .
|
4,216
|
private boolean containsIgnoreCase ( List < String > stringlist , String match ) { for ( String s : stringlist ) { if ( s . equalsIgnoreCase ( match ) ) { return true ; } } return false ; }
|
Checks if a list of string contains a String while ignoring case
|
4,217
|
private List < String > listToLowerCase ( List < String > l ) { List < String > result = new ArrayList < String > ( ) ; for ( String s : l ) { result . add ( s . toLowerCase ( ) ) ; } return result ; }
|
Converts a List of Strings to lower case Strings .
|
4,218
|
public String configurationInfo ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "MediaWikiParser configuration:\n" ) ; result . append ( "ParserClass: " + this . getClass ( ) + "\n" ) ; result . append ( "ShowImageText: " + showImageText + "\n" ) ; result . append ( "DeleteTags: " + deleteTags + "\n" ) ; result . append ( "ShowMathTagContent: " + showMathTagContent + "\n" ) ; result . append ( "CalculateSrcSpans: " + calculateSrcSpans + "\n" ) ; result . append ( "LanguageIdentifers: " ) ; for ( String s : languageIdentifers ) { result . append ( s + " " ) ; } result . append ( "\n" ) ; result . append ( "CategoryIdentifers: " ) ; for ( String s : categoryIdentifers ) { result . append ( s + " " ) ; } result . append ( "\n" ) ; result . append ( "ImageIdentifers: " ) ; for ( String s : imageIdentifers ) { result . append ( s + " " ) ; } result . append ( "\n" ) ; result . append ( "TemplateParser: " + templateParser . getClass ( ) + "\n" ) ; result . append ( templateParser . configurationInfo ( ) ) ; return result . toString ( ) ; }
|
Look at the MediaWikiParser interface for a description ...
|
4,219
|
private boolean runConfig ( ) { if ( lineSeparator == null ) { logger . debug ( "Set lineSeparator" ) ; return false ; } if ( categoryIdentifers == null ) { logger . warn ( "Set categoryIdentifers" ) ; return false ; } if ( languageIdentifers == null ) { logger . warn ( "Set languageIdentifers" ) ; return false ; } if ( imageIdentifers == null ) { logger . warn ( "Set imageIdentifers" ) ; return false ; } if ( templateParser == null ) { logger . warn ( "Set templateParser" ) ; return false ; } return true ; }
|
Checks if the configuration is runnable .
|
4,220
|
private void deleteTOCTag ( SpanManager sm ) { int temp = 0 ; while ( ( temp = sm . indexOf ( "__TOC__" , temp ) ) != - 1 ) { sm . delete ( temp , temp + 2 + 3 + 2 ) ; } temp = 0 ; while ( ( temp = sm . indexOf ( "__NOTOC__" , temp ) ) != - 1 ) { sm . delete ( temp , temp + 2 + 5 + 2 ) ; } }
|
Deleteing ALL TOC Tags
|
4,221
|
private lineType getLineType ( SpanManager sm , Span lineSpan ) { switch ( lineSpan . charAt ( 0 , sm ) ) { case '{' : if ( lineSpan . charAt ( 1 , sm ) == '|' ) { return lineType . TABLE ; } else { return lineType . PARAGRAPH ; } case '=' : if ( lineSpan . length ( ) > 2 && sm . charAt ( lineSpan . getEnd ( ) - 1 ) == '=' ) { return lineType . SECTION ; } else { return lineType . PARAGRAPH ; } case '-' : if ( lineSpan . charAt ( 1 , sm ) == '-' && lineSpan . charAt ( 2 , sm ) == '-' && lineSpan . charAt ( 3 , sm ) == '-' ) { return lineType . HR ; } else { return lineType . PARAGRAPH ; } case '*' : return lineType . NESTEDLIST ; case '#' : return lineType . NESTEDLIST_NR ; case ';' : return lineType . DEFINITIONLIST ; case ':' : if ( lineSpan . length ( ) > 1 ) { if ( lineSpan . length ( ) > 2 && lineSpan . charAt ( 1 , sm ) == '{' && lineSpan . charAt ( 2 , sm ) == '|' ) { return lineType . TABLE ; } else { return lineType . PARAGRAPH_INDENTED ; } } else { return lineType . PARAGRAPH ; } case ' ' : int nonWSPos = lineSpan . nonWSCharPos ( sm ) ; switch ( lineSpan . charAt ( nonWSPos , sm ) ) { case Span . ERRORCHAR : return lineType . EMPTYLINE ; case '{' : if ( lineSpan . charAt ( nonWSPos + 1 , sm ) == '|' ) { return lineType . TABLE ; } default : return lineType . PARAGRAPH_BOXED ; } case Span . ERRORCHAR : return lineType . EMPTYLINE ; default : return lineType . PARAGRAPH ; } }
|
Retunrns the Type of a line this is mainly done by the First Char of the Line ...
|
4,222
|
private int getSectionLevel ( SpanManager sm , Span sectionNameSpan ) { int begin = sectionNameSpan . getStart ( ) ; int end = sectionNameSpan . getEnd ( ) ; int level = 0 ; try { while ( ( sm . charAt ( begin + level ) == '=' ) && ( sm . charAt ( end - 1 - level ) == '=' ) ) { level ++ ; } } catch ( StringIndexOutOfBoundsException e ) { logger . debug ( "EXCEPTION IS OK: {}" , e . getLocalizedMessage ( ) ) ; } if ( begin + level == end ) { level = ( level - 1 ) / 2 ; } return level ; }
|
Returns the number of Equality Chars which are used to specify the level of the Section .
|
4,223
|
private SectionContainer buildSectionStructure ( List < SectionContent > scl ) { SectionContainer result = new SectionContainer ( 0 ) ; for ( SectionContent sContent : scl ) { int contentLevel = sContent . getLevel ( ) ; SectionContainer sContainer = result ; for ( int containerLevel = result . getLevel ( ) + 1 ; containerLevel < contentLevel ; containerLevel ++ ) { int containerSubSections = sContainer . nrOfSubSections ( ) ; if ( containerSubSections != 0 ) { Section temp = sContainer . getSubSection ( containerSubSections - 1 ) ; if ( temp . getClass ( ) == SectionContainer . class ) { sContainer = ( SectionContainer ) temp ; } else { SectionContainer sct = new SectionContainer ( temp . getTitleElement ( ) , containerLevel ) ; sct . addSection ( temp ) ; if ( calculateSrcSpans ) { sct . setSrcSpan ( temp . getSrcSpan ( ) ) ; } temp . setTitleElement ( null ) ; temp . setLevel ( containerLevel + 1 ) ; sContainer . removeSection ( temp ) ; sContainer . addSection ( sct ) ; sContainer = sct ; } } else { sContainer = new SectionContainer ( null , containerLevel ) ; } } sContainer . addSection ( sContent ) ; } if ( calculateSrcSpans ) { result . setSrcSpan ( new SrcSpan ( 0 , - 1 ) ) ; } return result ; }
|
Takes a list of SectionContent and returns a SectionContainer with the given SectionContent s in the right structure .
|
4,224
|
private static String getLinkNameSpace ( String target ) { int pos = target . indexOf ( ':' ) ; if ( pos == - 1 ) { return null ; } else { return target . substring ( 0 , pos ) . replace ( '_' , ' ' ) . trim ( ) . toLowerCase ( ) ; } }
|
Returns the LOWERCASE NameSpace of the link target
|
4,225
|
private void parseQuotedSpans ( SpanManager sm , Span s , List < Span > quotedSpans , String quotation ) { final int qlen = quotation . length ( ) ; int start = sm . indexOf ( quotation , s . getStart ( ) , s . getEnd ( ) ) ; while ( start != - 1 ) { int end = sm . indexOf ( quotation , start + qlen , s . getEnd ( ) ) ; if ( end == - 1 ) { break ; } Span qs = new Span ( start , end ) ; quotedSpans . add ( qs ) ; if ( calculateSrcSpans ) { qs . setSrcSpan ( new SrcSpan ( sm . getSrcPos ( start ) , sm . getSrcPos ( end + qlen - 1 ) + 1 ) ) ; } sm . delete ( end , end + qlen ) ; sm . delete ( start , start + qlen ) ; start = sm . indexOf ( quotation , qs . getEnd ( ) , s . getEnd ( ) ) ; } }
|
Searches the Range given by the Span s for the double occurence of quotation and puts the results in the List quotedSpans . The Quotation tags will be deleted .
|
4,226
|
private void parseBoldAndItalicSpans ( SpanManager sm , Span line , List < Span > boldSpans , List < Span > italicSpans ) { parseQuotedSpans ( sm , line , boldSpans , "'''" ) ; parseQuotedSpans ( sm , line , italicSpans , "''" ) ; int openTag = sm . indexOf ( "''" , line ) ; if ( openTag != - 1 ) { Span qs = new Span ( openTag , line . getEnd ( ) ) ; if ( calculateSrcSpans ) { qs . setSrcSpan ( new SrcSpan ( sm . getSrcPos ( openTag ) , sm . getSrcPos ( line . getEnd ( ) ) ) ) ; } if ( sm . indexOf ( "'''" , openTag , openTag + 3 ) != - 1 ) { boldSpans . add ( qs ) ; sm . delete ( openTag , openTag + 3 ) ; } else { italicSpans . add ( qs ) ; sm . delete ( openTag , openTag + 2 ) ; } } }
|
Searches a line for Bold and Italic quotations this has to be done linewhise .
|
4,227
|
public ContentElement parseContentElement ( String src ) { SpanManager sm = new SpanManager ( src ) ; ContentElementParsingParameters cepp = new ContentElementParsingParameters ( ) ; parseImagesAndInternalLinks ( sm , cepp . linkSpans , cepp . links ) ; LinkedList < Span > lineSpans = new LinkedList < Span > ( ) ; getLineSpans ( sm , lineSpans ) ; sm . removeManagedList ( lineSpans ) ; return ( parseContentElement ( sm , cepp , lineSpans , new ContentElement ( ) ) ) ; }
|
Building a ContentElement from a String
|
4,228
|
private ContentElement parseContentElement ( SpanManager sm , ContentElementParsingParameters cepp , Span lineSpan ) { LinkedList < Span > lineSpans = new LinkedList < Span > ( ) ; lineSpans . add ( lineSpan ) ; return parseContentElement ( sm , cepp , lineSpans , new ContentElement ( ) ) ; }
|
Building a ContentElement from a single line .
|
4,229
|
private static List < Link > sortLinks ( List < Link > links ) { List < Link > result = new ArrayList < Link > ( ) ; for ( Link l : links ) { int pos = 0 ; while ( pos < result . size ( ) && l . getPos ( ) . getStart ( ) > result . get ( pos ) . getPos ( ) . getStart ( ) ) { pos ++ ; } result . add ( pos , l ) ; } return result ; }
|
Sorts the Links ...
|
4,230
|
private static List < Template > sortTemplates ( List < Template > templates ) { List < Template > result = new ArrayList < Template > ( ) ; for ( Template t : templates ) { int pos = 0 ; while ( pos < result . size ( ) && t . getPos ( ) . getStart ( ) > result . get ( pos ) . getPos ( ) . getStart ( ) ) { pos ++ ; } result . add ( pos , t ) ; } return result ; }
|
Sorts the Templates ...
|
4,231
|
private void setFirstParagraph ( ParsedPage pp ) { int nr = pp . nrOfParagraphs ( ) ; for ( int i = 0 ; i < nr ; i ++ ) { Paragraph p = pp . getParagraph ( i ) ; SpanManager ptext = new SpanManager ( p . getText ( ) ) ; List < Span > delete = new ArrayList < Span > ( ) ; ptext . manageList ( delete ) ; List < Template > tl = p . getTemplates ( ) ; for ( int j = tl . size ( ) - 1 ; j >= 0 ; j -- ) { delete . add ( tl . get ( j ) . getPos ( ) ) ; } List < Span > sl = p . getFormatSpans ( FormatType . TAG ) ; for ( int j = sl . size ( ) - 1 ; j >= 0 ; j -- ) { delete . add ( sl . get ( j ) ) ; } if ( showImageText ) { List < Link > ll = p . getLinks ( Link . type . IMAGE ) ; for ( int j = ll . size ( ) - 1 ; j >= 0 ; j -- ) { delete . add ( ll . get ( j ) . getPos ( ) ) ; } } for ( int j = delete . size ( ) - 1 ; j >= 0 ; j -- ) { ptext . delete ( delete . remove ( j ) ) ; } int pos = ptext . indexOf ( lineSeparator ) ; while ( pos != - 1 ) { ptext . delete ( pos , pos + lineSeparator . length ( ) ) ; pos = ptext . indexOf ( lineSeparator ) ; } if ( ! ptext . toString ( ) . trim ( ) . equals ( "" ) ) { pp . setFirstParagraphNr ( i ) ; return ; } } }
|
Algorithm to identify the first paragraph of a ParsedPage
|
4,232
|
public static void printProgressInfo ( int counter , int size , int step , ProgressInfoMode mode , String text ) { if ( size < step ) { return ; } if ( counter % ( size / step ) == 0 ) { double progressPercent = counter * 100 / size ; progressPercent = 1 + Math . round ( progressPercent * 100 ) / 100.0 ; if ( mode . equals ( ApiUtilities . ProgressInfoMode . TEXT ) ) { logger . info ( text + ": " + progressPercent + " - " + OS . getUsedMemory ( ) + " MB" ) ; } else if ( mode . equals ( ApiUtilities . ProgressInfoMode . DOTS ) ) { System . out . print ( "." ) ; if ( progressPercent >= 100 ) { System . out . println ( ) ; } } } }
|
Prints a progress counter .
|
4,233
|
protected void bufferInsertRow ( String table , Object [ ] [ ] row ) throws IOException { StringBuffer sql = ( StringBuffer ) insertBuffers . get ( table ) ; if ( sql != null ) { if ( traits . supportsMultiRowInsert ( ) && ( sql . length ( ) < blockSize ) ) { sql . append ( ',' ) ; appendInsertValues ( sql , row ) ; return ; } else { flushInsertBuffer ( table ) ; } } sql = new StringBuffer ( blockSize ) ; synchronized ( sql ) { appendInsertStatement ( sql , table , row ) ; insertBuffers . put ( table , sql ) ; } }
|
default 512k inserts
|
4,234
|
public void add ( final Revision rev ) { int revIndex = rev . getRevisionCounter ( ) ; if ( this . mapping . containsKey ( revIndex ) ) { revIndex = this . mapping . get ( revIndex ) ; } ChronoFullRevision cfr = this . fullRevStorage . get ( rev . getRevisionCounter ( ) ) ; ChronoStorageBlock block = new ChronoStorageBlock ( cfr , revIndex , rev ) ; cfr . add ( block ) ; if ( revIndex < revisionIndex ) { block . setDelivered ( true ) ; return ; } clean ( ) ; if ( this . storage . containsKey ( revIndex ) ) { return ; } storage . put ( revIndex , block ) ; size += block . length ( ) ; if ( first == null ) { first = block ; last = block ; } else { ChronoStorageBlock previous = null , current = first ; do { if ( revIndex < current . getRevisionIndex ( ) ) { block . setIndexPrev ( previous ) ; block . setIndexNext ( current ) ; if ( previous != null ) { previous . setIndexNext ( block ) ; } current . setIndexPrev ( block ) ; if ( current == first ) { this . first = block ; } return ; } previous = current ; current = current . getIndexNext ( ) ; } while ( current != null ) ; previous . setIndexNext ( block ) ; block . setIndexPrev ( previous ) ; this . last = block ; } }
|
Adds a revision to the chrono storage .
|
4,235
|
public Revision remove ( ) { ChronoStorageBlock block = first ; this . revisionIndex = block . getRevisionIndex ( ) ; ChronoStorageBlock next = block . getIndexNext ( ) ; this . first = next ; if ( next != null ) { this . first . setIndexPrev ( null ) ; } else { this . last = null ; } block . setDelivered ( true ) ; ChronoFullRevision cfr = block . getChronoFullRevision ( ) ; cfr . remove ( block . getRevisionCounter ( ) ) ; if ( storage . remove ( block . getRevisionIndex ( ) ) == null ) { throw new RuntimeException ( "VALUE WAS NOT REMOVED FROM STORAGE" ) ; } Revision rev = block . getRev ( ) ; size -= rev . getRevisionText ( ) . length ( ) ; return rev ; }
|
Removes a revision from the chrono storage .
|
4,236
|
public Revision get ( final int revisionIndex ) { if ( this . storage . containsKey ( revisionIndex ) ) { ChronoStorageBlock block = this . storage . get ( revisionIndex ) ; return block . getRev ( ) ; } return null ; }
|
Returns the revision of the specified chrono storage block .
|
4,237
|
public void clean ( ) { ChronoFullRevision cfr = firstCFR ; totalSize = size ; while ( cfr != null ) { totalSize += cfr . size ( ) ; cfr = cfr . getNext ( ) ; } if ( totalSize < MAX_STORAGE_SIZE ) { return ; } cfr = firstCFR ; while ( cfr != null ) { totalSize += cfr . clean ( revisionIndex , 0 ) ; cfr = cfr . getNext ( ) ; } ChronoStorageBlock block ; while ( last != null && totalSize >= MAX_STORAGE_SIZE ) { block = last . getIndexPrev ( ) ; if ( storage . remove ( last . getRevisionIndex ( ) ) == null ) { throw new RuntimeException ( "VALUE WAS NOT REMOVED FROM STORAGE" ) ; } totalSize -= last . length ( ) ; size += last . length ( ) ; if ( block != null ) { block . setIndexNext ( null ) ; } last . setIndexPrev ( null ) ; cfr = last . getChronoFullRevision ( ) ; totalSize += cfr . size ( ) - cfr . clean ( revisionIndex , last . getRevisionIndex ( ) ) ; if ( last == first ) { first = null ; } last = block ; } }
|
Reduces the amount of used storage by discarding chrono storage blocks .
|
4,238
|
private void write ( final int val ) throws EncodingException { if ( val < 0 || val > 255 ) { throw ErrorFactory . createEncodingException ( ErrorKeys . DIFFTOOL_ENCODING_VALUE_OUT_OF_RANGE , "byte value out of range: " + val ) ; } this . stream . write ( val ) ; }
|
Writes a byte to the buffer .
|
4,239
|
public void writeBit ( final int bit ) throws EncodingException { if ( bit != 0 && bit != 1 ) { throw ErrorFactory . createEncodingException ( ErrorKeys . DIFFTOOL_ENCODING_VALUE_OUT_OF_RANGE , "bit value out of range: " + bit ) ; } this . buffer |= bit << ( 7 - this . bufferLength ) ; this . bufferLength ++ ; if ( bufferLength == 8 ) { write ( buffer ) ; this . bufferLength = 0 ; this . buffer = 0 ; } }
|
Writes a single bit to the buffer .
|
4,240
|
public void writeValue ( final int length , final int value ) throws EncodingException { if ( length > 31 ) { throw ErrorFactory . createEncodingException ( ErrorKeys . DIFFTOOL_ENCODING_VALUE_OUT_OF_RANGE , "more than maximum length: " + value ) ; } for ( int i = length - 1 ; i >= 0 ; i -- ) { writeBit ( ( value >> i ) & 1 ) ; } }
|
Writes a positive integer to the buffer .
|
4,241
|
public void write ( final byte [ ] bText ) throws EncodingException { writeFillBits ( ) ; int l = bText . length ; for ( int i = 0 ; i < l ; i ++ ) { write ( 0xFF & bText [ i ] ) ; } }
|
Writes the byte array to the buffer . The currently used buffer will be filled with zero bits before is is written in front of the byte - array .
|
4,242
|
public static String getOsType ( ) { String osType = "unknown" ; String osName = System . getProperty ( "os.name" ) ; if ( osName . contains ( "Windows" ) ) { osType = "Windows" ; } else if ( osName . contains ( "Linux" ) ) { osType = "Linux" ; } return osType ; }
|
Tries to determine the tpye of OS the application is running on . At the moment only Windows and Linux are supported .
|
4,243
|
public static double getUsedMemory ( ) { Runtime rt = Runtime . getRuntime ( ) ; long memLong = rt . totalMemory ( ) - rt . freeMemory ( ) ; double memDouble = memLong / ( 1024.0 * 1024.0 ) ; memDouble = Math . round ( memDouble * 100 ) / 100.0 ; return memDouble ; }
|
Gets the memory used by the JVM in MB .
|
4,244
|
public Set < Integer > getOutlinkIDs ( ) { Set < Integer > tmpSet = new HashSet < Integer > ( ) ; Session session = wiki . __getHibernateSession ( ) ; session . beginTransaction ( ) ; session . buildLockRequest ( LockOptions . NONE ) . lock ( hibernatePage ) ; tmpSet . addAll ( hibernatePage . getOutLinks ( ) ) ; session . getTransaction ( ) . commit ( ) ; return tmpSet ; }
|
The result set may also contain links from non - existing pages . It is in the responsibility of the user to check whether the page exists .
|
4,245
|
public void run ( ) { try { ArchiveManager archives = new ArchiveManager ( ) ; ArticleReaderInterface articleReader = null ; ArchiveDescription description = null ; Task < Revision > task = null ; DiffCalculatorInterface diffCalc ; if ( MODE_STATISTICAL_OUTPUT ) { diffCalc = new TimedDiffCalculator ( new TaskTransmitter ( ) ) ; } else { diffCalc = new DiffCalculator ( new TaskTransmitter ( ) ) ; } long start , time ; while ( archives . hasArchive ( ) ) { try { description = archives . getArchive ( ) ; ArticleFilter nameFilter = new ArticleFilter ( ) ; articleReader = InputFactory . getTaskReader ( description , nameFilter ) ; ArticleConsumerLogMessages . logArchiveRetrieved ( logger , description ) ; } catch ( ArticleReaderException e ) { articleReader = null ; ArticleConsumerLogMessages . logExceptionRetrieveArchive ( logger , description , e ) ; } while ( articleReader != null ) { try { if ( articleReader . hasNext ( ) ) { start = System . currentTimeMillis ( ) ; task = articleReader . next ( ) ; time = System . currentTimeMillis ( ) - start ; if ( task == null ) { continue ; } ArticleConsumerLogMessages . logArticleRead ( logger , task , time , articleReader . getBytePosition ( ) ) ; start = System . currentTimeMillis ( ) ; diffCalc . process ( task ) ; time = System . currentTimeMillis ( ) - start ; DiffConsumerLogMessages . logArticleProcessed ( logger , task , time ) ; } else { ArticleConsumerLogMessages . logNoMoreArticles ( logger , description ) ; articleReader = null ; } } catch ( ArticleReaderException e ) { ArticleConsumerLogMessages . logTaskReaderException ( logger , e ) ; articleReader . resetTaskCompleted ( ) ; } catch ( DiffException e ) { DiffConsumerLogMessages . logDiffException ( logger , e ) ; articleReader . resetTaskCompleted ( ) ; diffCalc . reset ( ) ; } } } diffCalc . closeTransmitter ( ) ; ArticleConsumerLogMessages . logNoMoreArchives ( logger ) ; } catch ( ConfigurationException e ) { DiffToolLogMessages . logException ( logger , e ) ; throw new RuntimeException ( e ) ; } catch ( UnsupportedEncodingException e ) { DiffToolLogMessages . logException ( logger , e ) ; throw new RuntimeException ( e ) ; } catch ( IOException e ) { DiffToolLogMessages . logException ( logger , e ) ; throw new RuntimeException ( e ) ; } catch ( TimeoutException e ) { DiffToolLogMessages . logException ( logger , e ) ; throw new RuntimeException ( e ) ; } catch ( Exception e ) { DiffToolLogMessages . logException ( logger , e ) ; throw new RuntimeException ( e ) ; } }
|
Runs the diff creation process
|
4,246
|
public void setTimeStamp ( final String timeStamp ) { String time = timeStamp . replace ( 'T' , ' ' ) ; time = time . replace ( 'Z' , ' ' ) ; this . timeStamp = Timestamp . valueOf ( time ) ; }
|
Sets the timestamp information .
|
4,247
|
public String readFragmentedUTF ( ) throws IOException { StringBuffer result = new StringBuffer ( super . readUTF ( ) ) ; boolean fragmentFlag = super . readBoolean ( ) ; while ( fragmentFlag != END_REACHED ) { result . append ( super . readUTF ( ) ) ; fragmentFlag = super . readBoolean ( ) ; } return result . toString ( ) ; }
|
Read a fragmented UTF - 8 String
|
4,248
|
public String readUTFAsArray ( ) throws IOException { byte [ ] buffer = new byte [ super . readInt ( ) ] ; super . read ( buffer , 0 , buffer . length ) ; return new String ( buffer , "UTF-8" ) ; }
|
Read a byte array formed UTF - 8 String
|
4,249
|
private String getPagesArticlesFile ( ) { String pagesArticlesFile = null ; String parseMessage = null ; if ( files . getInputPagesArticles ( ) != null ) { pagesArticlesFile = files . getInputPagesArticles ( ) ; parseMessage = "Discussions are unavailable" ; } if ( files . getInputPagesMetaCurrent ( ) != null ) { pagesArticlesFile = files . getInputPagesMetaCurrent ( ) ; parseMessage = "Discussions are available" ; } logger . log ( parseMessage ) ; return pagesArticlesFile ; }
|
Parse either pages - articles . xml or pages - meta - current . xml . If both files exist in the input directory pages - meta - current . xml will be favored .
|
4,250
|
public Span adjust ( int offset , int n ) { if ( offset < 0 ) return this ; if ( offset < end ) { end += n ; if ( end < offset ) end = offset ; } else return this ; if ( offset < start ) { start += n ; if ( start < offset ) start = offset ; } return this ; }
|
Adjusts the start and end Position of the Span if they are larger than the offset .
|
4,251
|
public Span trimTrail ( CharSequence src ) { if ( start < end ) { while ( src . charAt ( end - 1 ) == 32 ) { end -- ; if ( start == end ) break ; } } return this ; }
|
Returns the Span with trailing whitespaces omitted .
|
4,252
|
public Span trim ( CharSequence src ) { if ( start < end ) while ( src . charAt ( end - 1 ) == 32 ) { end -- ; if ( start == end ) break ; } if ( start < end ) while ( src . charAt ( start ) == 32 ) { start ++ ; if ( start == end ) break ; } return this ; }
|
Returns the Span with leading and trailing whitespaces omitted .
|
4,253
|
public long byteSize ( ) { long byteSize = 3 ; int size = parts . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { byteSize += this . parts . get ( i ) . byteSize ( ) ; } return byteSize ; }
|
Returns an estimation of the size used to stored the data .
|
4,254
|
public boolean isFullRevision ( ) { if ( this . parts . size ( ) == 1 ) { DiffPart p = this . parts . get ( 0 ) ; if ( p . getAction ( ) == DiffAction . FULL_REVISION_UNCOMPRESSED ) { return true ; } } return false ; }
|
Returns whether the revision described by this diff is a full revision or not .
|
4,255
|
private double computeAverageFanOut ( Iterable < Page > pages ) { Set < Integer > pageIDs = new HashSet < Integer > ( ) ; while ( pages . iterator ( ) . hasNext ( ) ) { pageIDs . add ( pages . iterator ( ) . next ( ) . getPageId ( ) ) ; } if ( pageIDs . isEmpty ( ) ) { logger . warn ( "Cannot compute average fan-out of an empty page set." ) ; return 0.0 ; } int fanOutCounter = 0 ; Session session = this . wiki . __getHibernateSession ( ) ; session . beginTransaction ( ) ; Iterator results = session . createQuery ( "select page.outLinks, page.pageId from Page as page" ) . list ( ) . iterator ( ) ; while ( results . hasNext ( ) ) { Object [ ] row = ( Object [ ] ) results . next ( ) ; Set outLinks = ( Set ) row [ 0 ] ; Integer pageId = ( Integer ) row [ 1 ] ; if ( pageIDs . contains ( pageId ) ) { fanOutCounter += outLinks . size ( ) ; } } session . getTransaction ( ) . commit ( ) ; return ( double ) fanOutCounter / this . getNumberOfPages ( ) ; }
|
Computes the average fan out of the page set . Fan out is the number of outgoing links per page .
|
4,256
|
private Map < Integer , Set < Integer > > getCategoryArticleMap ( Wikipedia pWiki , Set < Integer > pNodes ) throws WikiPageNotFoundException { Map < Integer , Set < Integer > > categoryArticleMap = new HashMap < Integer , Set < Integer > > ( ) ; int progress = 0 ; for ( int node : pNodes ) { progress ++ ; ApiUtilities . printProgressInfo ( progress , pNodes . size ( ) , 10 , ApiUtilities . ProgressInfoMode . TEXT , "Getting category-article map." ) ; Category cat = pWiki . getCategory ( node ) ; if ( cat != null ) { Set < Integer > pages = new HashSet < Integer > ( cat . __getPages ( ) ) ; categoryArticleMap . put ( node , pages ) ; } else { logger . info ( "{} is not a category." , node ) ; } } return categoryArticleMap ; }
|
Building a mapping from categories to article sets .
|
4,257
|
public void getGraphParameters ( CategoryGraph catGraph ) { double startTime = System . currentTimeMillis ( ) ; logger . error ( catGraph . getGraphInfo ( ) ) ; double endTime = ( System . currentTimeMillis ( ) - startTime ) / 1000.0 ; logger . error ( endTime + "s" ) ; }
|
Get various graph parameters like diameter average out - degree etc of the categroy graph .
|
4,258
|
public int getNumberOfCategorizedArticles ( Wikipedia pWiki , CategoryGraph catGraph ) throws WikiApiException { if ( categorizedArticleSet == null ) { iterateCategoriesGetArticles ( pWiki , catGraph ) ; } return categorizedArticleSet . size ( ) ; }
|
If the return value has been already computed it is returned else it is computed at retrieval time .
|
4,259
|
public Map < Integer , Integer > getDistributionOfArticlesByCategory ( Wikipedia pWiki , CategoryGraph catGraph ) throws WikiPageNotFoundException { if ( degreeDistribution == null ) { iterateCategoriesGetArticles ( pWiki , catGraph ) ; } return degreeDistribution ; }
|
Computes the distribution of the number of articles per category . If the return value has been already computed it is returned else it is computed at retrieval time .
|
4,260
|
private void verify ( final Task < Diff > task , final Diff decodedDiff , final Diff originalDiff ) throws SQLConsumerException { String orig = originalDiff . toString ( ) ; String deco = decodedDiff . toString ( ) ; boolean notEqual = ! orig . equals ( deco ) ; if ( notEqual && MODE_SURROGATES == SurrogateModes . REPLACE ) { char [ ] origDiff = orig . toCharArray ( ) ; if ( Surrogates . scan ( origDiff ) ) { String repDiff = new String ( Surrogates . replace ( origDiff ) ) ; notEqual = ! repDiff . equals ( deco ) ; } } if ( notEqual ) { if ( MODE_DEBUG_OUTPUT_ACTIVATED ) { try { WikipediaXMLWriter writer = new WikipediaXMLWriter ( LOGGING_PATH_DIFFTOOL + LOGGING_PATH_DEBUG + task . getHeader ( ) . getArticleName ( ) + ".dbg" ) ; switch ( task . getTaskType ( ) ) { case TASK_FULL : case TASK_PARTIAL_FIRST : writer . writeDiff ( task ) ; break ; case TASK_PARTIAL : case TASK_PARTIAL_LAST : { int revCount = originalDiff . getRevisionCounter ( ) ; Diff d ; boolean fullRev = false ; for ( int diffCount = 0 ; ! fullRev && diffCount < originalDiff . size ( ) ; diffCount ++ ) { d = task . get ( diffCount ) ; if ( d . getRevisionCounter ( ) <= revCount && d . isFullRevision ( ) ) { fullRev = true ; writer . writeDiff ( task , diffCount ) ; } } if ( ! fullRev ) { writer . writeDiffFile ( task ) ; } } break ; default : throw new IOException ( "Unknown TaskType" ) ; } writer . close ( ) ; } catch ( IOException e ) { ConsumerLogMessages . logException ( logger , e ) ; } } throw ErrorFactory . createSQLConsumerException ( ErrorKeys . DIFFTOOL_SQLCONSUMER_ENCODING_VERIFICATION_FAILED , "Redecoding of " + task . getHeader ( ) . getArticleName ( ) + " failed at revision " + originalDiff . getRevisionCounter ( ) + "." ) ; } }
|
Verifies that the decoded diff is identical to the original diff .
|
4,261
|
public void writeFragmentedUTF ( String str ) throws IOException { if ( str . length ( ) <= MAX_LENGTH ) { writeLastUTFFragment ( str ) ; } else { writeUTFFragment ( str . substring ( 0 , MAX_LENGTH ) ) ; writeFragmentedUTF ( str . substring ( MAX_LENGTH ) ) ; } }
|
The UTF - 8 encoding uses sequences of 1 2 or 3 bytes per character . With he maximal length of the fragment we want to ensure that there are no overflow of 65536 byte sized buffer
|
4,262
|
private void validate7ZipSettings ( ) { boolean flag = controller . is7ZipEnabled ( ) ; sevenZipEnableBox . setSelected ( flag ) ; sevenZipLabel . setEnabled ( flag ) ; sevenZipPathField . setEnabled ( flag ) ; sevenZipSearchButton . setEnabled ( flag ) ; }
|
Validates the 7Zip settings
|
4,263
|
public MediaWikiParser createParser ( ) { logger . debug ( "Selected Parser: {}" , parserClass ) ; if ( parserClass == ModularParser . class ) { ModularParser mwgp = new ModularParser ( "\n" , languageIdentifers , categoryIdentifers , imageIdentifers , showImageText , deleteTags , showMathTagContent , calculateSrcSpans , null ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( lineSeparator + "languageIdentifers: " ) ; for ( String s : languageIdentifers ) { sb . append ( s + " " ) ; } sb . append ( lineSeparator + "categoryIdentifers: " ) ; for ( String s : categoryIdentifers ) { sb . append ( s + " " ) ; } sb . append ( lineSeparator + "imageIdentifers: " ) ; for ( String s : imageIdentifers ) { sb . append ( s + " " ) ; } logger . debug ( sb . toString ( ) ) ; MediaWikiTemplateParser mwtp ; logger . debug ( "Selected TemplateParser: {}" , templateParserClass ) ; if ( templateParserClass == GermanTemplateParser . class ) { for ( String s : deleteTemplates ) { logger . debug ( "DeleteTemplate: '{}'" , s ) ; } for ( String s : parseTemplates ) { logger . debug ( "ParseTemplate: '{}'" , s ) ; } mwtp = new GermanTemplateParser ( mwgp , deleteTemplates , parseTemplates ) ; } else if ( templateParserClass == FlushTemplates . class ) { mwtp = new FlushTemplates ( ) ; } else if ( templateParserClass == ShowTemplateNamesAndParameters . class ) { mwtp = new ShowTemplateNamesAndParameters ( ) ; } else { logger . error ( "TemplateParser Class Not Found!" ) ; return null ; } mwgp . setTemplateParser ( mwtp ) ; return mwgp ; } else { logger . error ( "Parser Class Not Found!" ) ; return null ; } }
|
Creates a MediaWikiParser with the configurations which has been set .
|
4,264
|
public static String getSetContents ( Set s ) { StringBuffer sb = new StringBuffer ( 1000 ) ; Object [ ] sortedArray = s . toArray ( ) ; Arrays . sort ( sortedArray ) ; int counter = 0 ; int elementsPerRow = 10 ; for ( Object element : sortedArray ) { sb . append ( element . toString ( ) + " " ) ; counter ++ ; if ( ( counter % elementsPerRow ) == 0 ) { sb . append ( System . getProperty ( "line.separator" ) ) ; } } sb . append ( System . getProperty ( "line.separator" ) ) ; return sb . toString ( ) ; }
|
Debug output an internal set structure .
|
4,265
|
public static String getMapContents ( Map m ) { StringBuffer sb = new StringBuffer ( 1000 ) ; Object [ ] sortedArray = m . keySet ( ) . toArray ( ) ; Arrays . sort ( sortedArray ) ; for ( Object element : sortedArray ) { sb . append ( element . toString ( ) + " - " + m . get ( element ) + System . getProperty ( "line.separator" ) ) ; } return sb . toString ( ) ; }
|
Debug output an internal map structure as key - value pairs .
|
4,266
|
public static void logDiffException ( final Logger logger , final DiffException e ) { logger . logException ( Level . ERROR , "DiffException" , e ) ; }
|
Logs the occurance of a DiffException .
|
4,267
|
public static void logInvalidTaskType ( final Logger logger , final TaskTypes type ) { logger . logMessage ( Level . INFO , "Invalid TaskType: " + type ) ; }
|
Logs the occurance of an invalid task type .
|
4,268
|
public static void logStartArticleProcessing ( final Logger logger , final Task < Revision > article , long time , long transmittingTime ) { logger . logMessage ( Level . TRACE , "Start Procssing Task\t" + article . toString ( ) ) ; }
|
Logs the start of the processing of an revision task .
|
4,269
|
private void initializePrefixes ( ) { if ( namespaceMap == null ) { System . err . println ( "Cannot use whitespace filter without initializing the namespace-prefix map for the current Wikipedia language version. DISABLING FILTER." ) ; } else { prefixesToAllow = new HashSet < String > ( ) ; prefixesToReject = new HashSet < String > ( ) ; for ( Entry < Integer , String > namespace : namespaceMap . entrySet ( ) ) { if ( allowedNamespaces . contains ( namespace . getKey ( ) ) ) { prefixesToAllow . add ( namespace . getValue ( ) + ":" ) ; } else { prefixesToReject . add ( namespace . getValue ( ) + ":" ) ; } } } }
|
Initialize allowed and restricted prefixes
|
4,270
|
public boolean checkArticle ( String title ) { if ( namespaceMap == null || namespaceMap . size ( ) == 0 || allowedNamespaces == null || allowedNamespaces . size ( ) == 0 ) { return true ; } else { for ( String str : prefixesToReject ) { if ( title . startsWith ( str ) ) { return false ; } } for ( String str : prefixesToAllow ) { if ( title . startsWith ( str ) ) { return true ; } if ( excludeMainNamespace ) { return false ; } } return true ; } }
|
Filter any pages by title prefixes
|
4,271
|
public void setSectionHandling ( Map < String , EnumMap < SIT , EnumMap < CIT , Boolean > > > sectionHandling ) { this . sectionHandling = sectionHandling ; }
|
Be sure to set the Default Section Handling to avoid errors ...
|
4,272
|
public void addSectionHandling ( int level , EnumMap < SIT , EnumMap < CIT , Boolean > > sh ) { sectionHandling . put ( SectionType . SECTION_LEVEL . toString ( ) + level , sh ) ; }
|
adds section handling for a specified relative level ...
|
4,273
|
public void addSectionHandling ( String name , EnumMap < SIT , EnumMap < CIT , Boolean > > sh ) { sectionHandling . put ( SectionType . USER_SECTION . toString ( ) + name . toUpperCase ( ) , sh ) ; }
|
adds section handling for a specila section name ...
|
4,274
|
public void setDefaultSectionHandling ( EnumMap < SIT , EnumMap < CIT , Boolean > > sh ) { sectionHandling . put ( SectionType . DEFAULT_SECTION . toString ( ) , sh ) ; }
|
sets the section handling for all sections which are not set by level or name ...
|
4,275
|
public String getSelectionInfo ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "SelectionInfo: " + this . getClass ( ) . toString ( ) + "\n" ) ; result . append ( "Page:" + CITInfo ( pageHandling ) + "\n" ) ; result . append ( "FirstParagraph:" + CITInfo ( firstParagraphHandling ) + "\n" ) ; for ( String key : sectionHandling . keySet ( ) ) { final String uss = SectionType . USER_SECTION . toString ( ) ; if ( key . startsWith ( uss ) ) result . append ( uss + "[" + key . substring ( uss . length ( ) ) + "]:\n" ) ; else result . append ( key + ":\n" ) ; result . append ( SITInfo ( sectionHandling . get ( key ) ) + "\n" ) ; } return result . toString ( ) ; }
|
Returns information which infomations are selected by the actual configuration
|
4,276
|
public static String CITInfo ( EnumMap < CIT , Boolean > hp ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "[" ) ; if ( hp != null ) { for ( CIT key : hp . keySet ( ) ) result . append ( key . toString ( ) + ":" + hp . get ( key ) + ", " ) ; result . delete ( result . length ( ) - 2 , result . length ( ) ) ; } result . append ( "]" ) ; return result . toString ( ) ; }
|
Converts a CITMap into a human readable String
|
4,277
|
public static String SITInfo ( EnumMap < SIT , EnumMap < CIT , Boolean > > shp ) { StringBuilder result = new StringBuilder ( ) ; for ( SIT key : shp . keySet ( ) ) { result . append ( "\t" + key . toString ( ) + ":" + CITInfo ( shp . get ( key ) ) + "\n" ) ; } return result . toString ( ) ; }
|
Converts a SITMap into a human readable String
|
4,278
|
public String getSelectedText ( ParsedPage pp ) { if ( pp == null ) return null ; StringBuilder sb = new StringBuilder ( ) ; levelModifier = pp . getSection ( 0 ) . getLevel ( ) - 1 ; if ( pageHandling == null ) { if ( firstParagraphHandling != null ) { handleContent ( pp . getFirstParagraph ( ) , firstParagraphHandling , sb ) ; deleteParagraph ( pp . getFirstParagraphNr ( ) , pp . getSections ( ) ) ; } for ( Section s : pp . getSections ( ) ) handleSection ( s , sb ) ; } else { if ( pageHandling . get ( CIT . TEXT ) ) { sb . append ( pp . getText ( ) ) ; } else { if ( pageHandling . get ( CIT . BOLD ) ) { handleSpans ( pp . getFormatSpans ( FormatType . BOLD ) , pp . getText ( ) , sb ) ; } if ( pageHandling . get ( CIT . ITALIC ) ) { handleSpans ( pp . getFormatSpans ( FormatType . ITALIC ) , pp . getText ( ) , sb ) ; } } if ( pageHandling . get ( CIT . LINK ) ) handleLinks ( pp . getLinks ( ) , ! pageHandling . get ( CIT . TEXT ) , sb ) ; } return sb . toString ( ) . trim ( ) ; }
|
Returns the Information of a ParsedPage which are selected by the actual configuration
|
4,279
|
public String toClock ( ) { StringBuilder s = new StringBuilder ( ) ; s . append ( ( ( this . weeks * 7 + this . days ) * 24 + this . hours ) + ":" ) ; if ( this . minutes < 10 ) { s . append ( '0' ) ; } s . append ( this . minutes + ":" ) ; if ( this . seconds < 10 ) { s . append ( '0' ) ; } s . append ( this . seconds + "." ) ; if ( this . milliseconds < 100 ) { s . append ( '0' ) ; } if ( this . milliseconds < 10 ) { s . append ( '0' ) ; } s . append ( this . milliseconds ) ; return s . toString ( ) ; }
|
Returns the clock description of the time value .
|
4,280
|
public static String toClock ( long time ) { long ttime = time ; short miliseconds = ( short ) ( ttime % 1000 ) ; ttime = ttime / 1000 ; short seconds = ( short ) ( ttime % 60 ) ; ttime = ttime / 60 ; short minutes = ( short ) ( ttime % 60 ) ; ttime = ttime / 60 ; short hours = ( short ) ( ttime % 24 ) ; ttime = ttime / 24 ; short days = ( short ) ( ttime % 7 ) ; short weeks = ( short ) ( ttime / 7 ) ; StringBuilder s = new StringBuilder ( ) ; s . append ( ( ( weeks * 7 + days ) * 24 + hours ) + ":" ) ; if ( minutes < 10 ) { s . append ( '0' ) ; } s . append ( minutes + ":" ) ; if ( seconds < 10 ) { s . append ( '0' ) ; } s . append ( seconds + "." ) ; if ( miliseconds < 100 ) { s . append ( '0' ) ; } if ( miliseconds < 10 ) { s . append ( '0' ) ; } s . append ( miliseconds ) ; return s . toString ( ) ; }
|
Transforms a millisecond value to the clock representation .
|
4,281
|
public Object getValueAt ( final int row , final int col ) { switch ( col ) { case 0 : return archives . get ( row ) . getType ( ) ; case 1 : return archives . get ( row ) . getStartPosition ( ) ; case 2 : return archives . get ( row ) . getPath ( ) ; } return "---" ; }
|
Returns the value at the specified position .
|
4,282
|
public void applyConfiguration ( final ConfigSettings config ) { clear ( ) ; Iterator < ArchiveDescription > aIt = config . archiveIterator ( ) ; while ( aIt . hasNext ( ) ) { addArchive ( aIt . next ( ) ) ; } }
|
Adds the ArchiveDescriptions contained in the configuration .
|
4,283
|
private boolean queryArticle ( ) throws SQLException { Statement statement = this . connection . createStatement ( ) ; String query = "SELECT ArticleID, FullRevisionPKs, RevisionCounter " + "FROM index_articleID_rc_ts " + "WHERE articleID > " + this . currentArticleID + " LIMIT " + MAX_NUMBER_RESULTS ; resultArticles = statement . executeQuery ( query ) ; if ( resultArticles . next ( ) ) { this . currentArticleID = resultArticles . getInt ( 1 ) ; return ( this . lastArticleID == - 1 ) || ( this . currentArticleID <= this . lastArticleID ) ; } return false ; }
|
Retrieves the next articles from the article index .
|
4,284
|
private Revision init ( ) throws WikiApiException { try { currentArticleID = resultArticles . getInt ( 1 ) ; String fullRevisionPKs = resultArticles . getString ( 2 ) ; String revisionCounters = resultArticles . getString ( 3 ) ; int index = revisionCounters . lastIndexOf ( ' ' ) ; if ( index == - 1 ) { throw new RuntimeException ( "Invalid revisioncounter content" ) ; } this . maxRevision = Integer . parseInt ( revisionCounters . substring ( index + 1 , revisionCounters . length ( ) ) ) ; Statement statement = null ; ResultSet result = null ; try { statement = this . connection . createStatement ( ) ; result = statement . executeQuery ( "SELECT Mapping " + "FROM index_chronological " + "WHERE ArticleID=" + currentArticleID + " LIMIT 1" ) ; if ( result . next ( ) ) { this . modus = ITERATE_WITH_MAPPING ; this . chronoIterator = new ChronoIterator ( config , connection , result . getString ( 1 ) , fullRevisionPKs , revisionCounters ) ; if ( this . chronoIterator . hasNext ( ) ) { return this . chronoIterator . next ( ) ; } else { throw new RuntimeException ( "cIt Revision query failed" ) ; } } else { this . modus = ITERATE_WITHOUT_MAPPING ; index = fullRevisionPKs . indexOf ( ' ' ) ; if ( index == - 1 ) { index = fullRevisionPKs . length ( ) ; } int currentPK = Integer . parseInt ( fullRevisionPKs . substring ( 0 , index ) ) ; this . revisionIterator = new RevisionIterator ( config , currentPK , currentPK + maxRevision - 2 , connection ) ; if ( revisionIterator . hasNext ( ) ) { return revisionIterator . next ( ) ; } else { throw new RuntimeException ( "Revision query failed" ) ; } } } finally { if ( statement != null ) { statement . close ( ) ; } if ( result != null ) { result . close ( ) ; } } } catch ( WikiApiException e ) { throw e ; } catch ( Exception e ) { throw new WikiApiException ( e ) ; } }
|
Initiates the iteration over of a new article .
|
4,285
|
private void initTable ( ) { namespaces = new JTable ( new FilterTableModel ( ) ) ; namespaces . removeColumn ( namespaces . getColumn ( "#" ) ) ; namespaces . setFillsViewportHeight ( true ) ; namespaces . setPreferredScrollableViewportSize ( new Dimension ( 500 , 70 ) ) ; JScrollPane scrollPane = new JScrollPane ( namespaces ) ; scrollPane . setBounds ( 70 , 10 , 300 , 200 ) ; this . add ( scrollPane ) ; }
|
Initialize JTable that contains namespaces
|
4,286
|
public static void logError ( final Logger logger , final Error e ) { logger . logError ( Level . ERROR , "Unexpected Error" , e ) ; }
|
Logs an error .
|
4,287
|
public static void logException ( final Logger logger , final Exception e ) { logger . logException ( Level . ERROR , "Unexpected Exception" , e ) ; }
|
Logs an exception .
|
4,288
|
public static void logStatus ( final Logger logger , final long startTime , final long sleepingTime , final long workingTime ) { logger . logMessage ( Level . DEBUG , "Consumer-Status-Report [" + Time . toClock ( System . currentTimeMillis ( ) - startTime ) + "]" + "\tEFFICIENCY\t " + MathUtilities . percentPlus ( workingTime , sleepingTime ) + "\tWORK [" + Time . toClock ( workingTime ) + "]" + "\tSLEEP [" + Time . toClock ( sleepingTime ) + "]" ) ; }
|
Logs the status of the consumer .
|
4,289
|
public static void logTimeoutException ( final Logger logger , final TimeoutException e ) { logger . logException ( Level . WARN , "TimeoutException" , e ) ; }
|
Logs the occurrence of a TimeoutException .
|
4,290
|
public static Logger createLogger ( final LoggerType type , final String consumerName ) throws LoggingException { Logger log = new Logger ( type , consumerName ) ; if ( consumerLoggingIndex . put ( consumerName , log ) != null ) { throw ErrorFactory . createLoggingException ( ErrorKeys . LOGGING_LOGGINGFACTORY_LOGGER_ALREADY_EXIST ) ; } return log ; }
|
Creates a new Logger .
|
4,291
|
public static Logger getLogger ( final String consumerName ) throws LoggingException { Logger log = consumerLoggingIndex . get ( consumerName ) ; if ( log == null ) { throw ErrorFactory . createLoggingException ( ErrorKeys . LOGGING_LOGGINGFACTORY_NO_SUCH_LOGGER ) ; } return log ; }
|
Returns an already created Logger .
|
4,292
|
public Diff decode ( ) throws UnsupportedEncodingException , DecodingException { int header = r . read ( 3 ) ; if ( DiffAction . parse ( header ) != DiffAction . DECODER_DATA ) { throw new DecodingException ( "Invalid codecData code: " + header ) ; } int blockSize_C = 3 ; int blockSize_S = r . read ( 5 ) ; int blockSize_E = r . read ( 5 ) ; int blockSize_B = r . read ( 5 ) ; int blockSize_L = r . read ( 5 ) ; r . read ( 1 ) ; if ( blockSize_S < 0 || blockSize_S > 31 ) { throw new DecodingException ( "blockSize_S out of range: " + blockSize_S ) ; } if ( blockSize_E < 0 || blockSize_E > 31 ) { throw new DecodingException ( "blockSize_E out of range: " + blockSize_E ) ; } if ( blockSize_B < 0 || blockSize_B > 31 ) { throw new DecodingException ( "blockSize_B out of range: " + blockSize_B ) ; } if ( blockSize_L < 0 || blockSize_L > 31 ) { throw new DecodingException ( "blockSize_L out of range: " + blockSize_L ) ; } return decode ( blockSize_C , blockSize_S , blockSize_E , blockSize_B , blockSize_L ) ; }
|
Decodes the information and returns the Diff .
|
4,293
|
private Diff decode ( final int blockSize_C , final int blockSize_S , final int blockSize_E , final int blockSize_B , final int blockSize_L ) throws UnsupportedEncodingException , DecodingException { int code = r . read ( blockSize_C ) ; Diff diff = new Diff ( ) ; while ( code != - 1 ) { switch ( DiffAction . parse ( code ) ) { case FULL_REVISION_UNCOMPRESSED : diff . add ( decodeFullRevision ( blockSize_L ) ) ; break ; case INSERT : diff . add ( decodeAdd ( blockSize_S , blockSize_L ) ) ; break ; case DELETE : diff . add ( decodeDelete ( blockSize_S , blockSize_E ) ) ; break ; case REPLACE : diff . add ( decodeReplace ( blockSize_S , blockSize_E , blockSize_L ) ) ; break ; case CUT : diff . add ( decodeCut ( blockSize_S , blockSize_E , blockSize_B ) ) ; break ; case PASTE : diff . add ( decodePaste ( blockSize_S , blockSize_B , r ) ) ; break ; default : throw new DecodingException ( "Invalid block_c code: " + code ) ; } code = r . read ( blockSize_C ) ; } return diff ; }
|
Decodes the information after the codec was successfully decoded and returns the Diff .
|
4,294
|
private DiffPart decodeAdd ( final int blockSize_S , final int blockSize_L ) throws UnsupportedEncodingException , DecodingException { if ( blockSize_S < 1 || blockSize_L < 1 ) { throw new DecodingException ( "Invalid value for blockSize_S: " + blockSize_S + " or blockSize_L: " + blockSize_L ) ; } int s = r . read ( blockSize_S ) ; int l = r . read ( blockSize_L ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; for ( int i = 0 ; i < l ; i ++ ) { output . write ( r . readByte ( ) ) ; } DiffPart part = new DiffPart ( DiffAction . INSERT ) ; part . setStart ( s ) ; part . setText ( output . toString ( WIKIPEDIA_ENCODING ) ) ; return part ; }
|
Decodes an Add operation .
|
4,295
|
private DiffPart decodeCut ( final int blockSize_S , final int blockSize_E , final int blockSize_B ) throws DecodingException { if ( blockSize_S < 1 || blockSize_E < 1 || blockSize_B < 1 ) { throw new DecodingException ( "Invalid value for blockSize_S: " + blockSize_S + ", blockSize_E: " + blockSize_E + " or blockSize_B: " + blockSize_B ) ; } int s = r . read ( blockSize_S ) ; int e = r . read ( blockSize_E ) ; int b = r . read ( blockSize_B ) ; DiffPart part = new DiffPart ( DiffAction . CUT ) ; part . setStart ( s ) ; part . setLength ( e ) ; part . setText ( Integer . toString ( b ) ) ; r . skip ( ) ; return part ; }
|
Decodes a Cut operation .
|
4,296
|
private DiffPart decodeDelete ( final int blockSize_S , final int blockSize_E ) throws DecodingException { if ( blockSize_S < 1 || blockSize_E < 1 ) { throw new DecodingException ( "Invalid value for blockSize_S: " + blockSize_S + " or blockSize_E: " + blockSize_E ) ; } int s = r . read ( blockSize_S ) ; int e = r . read ( blockSize_E ) ; DiffPart part = new DiffPart ( DiffAction . DELETE ) ; part . setStart ( s ) ; part . setLength ( e ) ; r . skip ( ) ; return part ; }
|
Decodes a Delete operation .
|
4,297
|
private DiffPart decodeFullRevision ( final int blockSize_L ) throws UnsupportedEncodingException , DecodingException { if ( blockSize_L < 1 ) { throw new DecodingException ( "Invalid value for blockSize_L: " + blockSize_L ) ; } int l = r . read ( blockSize_L ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; for ( int i = 0 ; i < l ; i ++ ) { output . write ( r . readByte ( ) ) ; } DiffPart part = new DiffPart ( DiffAction . FULL_REVISION_UNCOMPRESSED ) ; part . setText ( output . toString ( WIKIPEDIA_ENCODING ) ) ; return part ; }
|
Decodes a FullRevision operation .
|
4,298
|
private DiffPart decodePaste ( final int blockSize_S , final int blockSize_B , final BitReader r ) throws DecodingException { if ( blockSize_S < 1 || blockSize_B < 1 ) { throw new DecodingException ( "Invalid value for blockSize_S: " + blockSize_S + " or blockSize_B: " + blockSize_B ) ; } int s = r . read ( blockSize_S ) ; int b = r . read ( blockSize_B ) ; DiffPart part = new DiffPart ( DiffAction . PASTE ) ; part . setStart ( s ) ; part . setText ( Integer . toString ( b ) ) ; r . skip ( ) ; return part ; }
|
Decodes a Paste operation .
|
4,299
|
private DiffPart decodeReplace ( final int blockSize_S , final int blockSize_E , final int blockSize_L ) throws UnsupportedEncodingException , DecodingException { if ( blockSize_S < 1 || blockSize_E < 1 || blockSize_L < 1 ) { throw new DecodingException ( "Invalid value for blockSize_S: " + blockSize_S + ", blockSize_E: " + blockSize_E + " or blockSize_L: " + blockSize_L ) ; } int s = r . read ( blockSize_S ) ; int e = r . read ( blockSize_E ) ; int l = r . read ( blockSize_L ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; for ( int i = 0 ; i < l ; i ++ ) { output . write ( r . readByte ( ) ) ; } DiffPart part = new DiffPart ( DiffAction . REPLACE ) ; part . setStart ( s ) ; part . setLength ( e ) ; part . setText ( output . toString ( WIKIPEDIA_ENCODING ) ) ; return part ; }
|
Decodes a Replace operation .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.