idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
4,300
|
private byte [ ] inflateInput ( final byte [ ] zipinput , final int start ) { ByteArrayOutputStream stream ; try { byte [ ] compressedInput = zipinput ; Inflater decompresser = new Inflater ( ) ; decompresser . setInput ( compressedInput , start , compressedInput . length - start ) ; byte [ ] output = new byte [ 1000 ] ; stream = new ByteArrayOutputStream ( ) ; int cLength ; do { cLength = decompresser . inflate ( output ) ; stream . write ( output , 0 , cLength ) ; } while ( cLength == 1000 ) ; } catch ( DataFormatException e ) { throw new RuntimeException ( e ) ; } return stream . toByteArray ( ) ; }
|
Inflates the zipped input .
|
4,301
|
public void setInput ( final byte [ ] input ) { if ( input [ 0 ] == - 128 ) { r = new BitReader ( inflateInput ( input , 1 ) ) ; } else { r = new BitReader ( input ) ; } }
|
Assigns the binary input .
|
4,302
|
public void setInput ( final InputStream input , final boolean binary ) throws IOException { if ( ! binary ) { int v = input . read ( ) ; StringBuilder buffer = new StringBuilder ( ) ; boolean zipFlag = ( char ) v == '_' ; if ( zipFlag ) { v = input . read ( ) ; } while ( v != - 1 ) { buffer . append ( ( char ) v ) ; v = input . read ( ) ; } if ( zipFlag ) { r = new BitReader ( inflateInput ( Base64 . decodeBase64 ( buffer . toString ( ) ) , 0 ) ) ; } else { r = new BitReader ( Base64 . decodeBase64 ( buffer . toString ( ) ) ) ; } } else { ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; byte [ ] bData ; int l = input . available ( ) ; while ( l != 0 ) { bData = new byte [ l ] ; if ( input . read ( bData ) != l ) { throw new RuntimeException ( "ILLEGAL NUMBER OF BYTES READ" ) ; } stream . write ( bData ) ; l = input . available ( ) ; } if ( input . read ( ) != - 1 ) { throw new RuntimeException ( "END OF STREAM NOT REACHED" ) ; } bData = stream . toByteArray ( ) ; boolean zipFlag = bData [ 0 ] == - 128 ; if ( zipFlag ) { r = new BitReader ( inflateInput ( bData , 1 ) ) ; } else { r = new BitReader ( bData ) ; } } }
|
Assigns an input stream .
|
4,303
|
public void setInput ( final String input ) throws DecodingException { boolean zipFlag = input . charAt ( 0 ) == '_' ; if ( zipFlag ) { r = new BitReader ( inflateInput ( Base64 . decodeBase64 ( input . substring ( 1 ) ) , 0 ) ) ; } else { byte [ ] data = Base64 . decodeBase64 ( input ) ; if ( data == null ) { for ( int i = 0 ; i < input . length ( ) ; i ++ ) { System . err . println ( i + ": " + ( int ) input . charAt ( i ) + " <> " + input . charAt ( i ) ) ; } throw new DecodingException ( "BASE 64 DECODING FAILED: " + input ) ; } r = new BitReader ( data ) ; } }
|
Assigns base 64 encoded input .
|
4,304
|
public int totalSizeInBits ( ) { if ( converted ) { return 24 + this . countC * 3 + this . countS * blocksize_S + this . countE * blocksize_E + this . countB * blocksize_B + this . countL * blocksize_L + this . countT * 8 ; } converted = true ; if ( this . blocksize_B > 0 ) { this . blocksize_B = ( int ) Math . ceil ( Math . log ( blocksize_B + 1 ) / Math . log ( 2. ) ) ; } else if ( this . countB > 0 ) { this . blocksize_B = 1 ; } if ( this . blocksize_E > 0 ) { this . blocksize_E = ( int ) Math . ceil ( Math . log ( blocksize_E + 1 ) / Math . log ( 2. ) ) ; } else if ( this . countE > 0 ) { this . blocksize_E = 1 ; } if ( this . blocksize_L > 0 ) { this . blocksize_L = ( int ) Math . ceil ( Math . log ( blocksize_L + 1 ) / Math . log ( 2. ) ) ; } else if ( this . countL > 0 ) { this . blocksize_L = 1 ; } if ( this . blocksize_S > 0 ) { this . blocksize_S = ( int ) Math . ceil ( Math . log ( blocksize_S + 1 ) / Math . log ( 2. ) ) ; } else if ( this . countS > 0 ) { this . blocksize_S = 1 ; } return 24 + this . countC * 3 + this . countS * blocksize_S + this . countE * blocksize_E + this . countB * blocksize_B + this . countL * blocksize_L + this . countT * 8 ; }
|
Converts the input information into their log2 values . If an operation is contained in the diff the minimum number of bits used to encode this block is 1 byte .
|
4,305
|
private void validateDebugSettings ( ) { verifyDiffCheckBox . setSelected ( controller . isDiffVerificationEnabled ( ) ) ; verifyEncodingCheckBox . setSelected ( controller . isEncodingVerificationEnabled ( ) ) ; statsOutputCheckBox . setSelected ( controller . isStatsOutputEnabled ( ) ) ; boolean flagA = controller . isDiffVerificationEnabled ( ) || controller . isEncodingVerificationEnabled ( ) ; debugOuputCheckBox . setEnabled ( flagA ) ; debugOuputCheckBox . setSelected ( controller . isDebugOutputEnabled ( ) ) ; boolean flagB = controller . isDebugOutputEnabled ( ) ; debugOutputLabel . setEnabled ( flagA && flagB ) ; debugOutputField . setEnabled ( flagA && flagB ) ; }
|
Validates the debug settings .
|
4,306
|
public int read ( final int length ) throws DecodingException { if ( length > 31 ) { throw ErrorFactory . createDecodingException ( ErrorKeys . DIFFTOOL_DECODING_VALUE_OUT_OF_RANGE , "more than maximum length: " + length ) ; } int v , b = 0 ; for ( int i = length - 1 ; i >= 0 ; i -- ) { v = readBit ( ) ; if ( v == - 1 ) { if ( i != length - 1 ) { throw ErrorFactory . createDecodingException ( ErrorKeys . DIFFTOOL_DECODING_UNEXPECTED_END_OF_STREAM ) ; } return - 1 ; } b |= v << i ; } return b ; }
|
Reads the next length - bits from the input .
|
4,307
|
private boolean query ( ) throws SQLException { statement = this . connection . createStatement ( ) ; String query = "SELECT PrimaryKey, RevisionCounter," + " RevisionID, ArticleID, Timestamp, FullRevisionID " + "FROM revisions" ; if ( primaryKey > 0 ) { query += " WHERE PrimaryKey > " + primaryKey ; } if ( MAX_NUMBER_RESULTS > 0 ) { query += " LIMIT " + MAX_NUMBER_RESULTS ; } result = statement . executeQuery ( query ) ; return result . next ( ) ; }
|
Queries the database for more revision information .
|
4,308
|
public boolean hasNext ( ) { try { if ( result != null && result . next ( ) ) { return true ; } if ( this . statement != null ) { this . statement . close ( ) ; } if ( this . result != null ) { this . result . close ( ) ; } return query ( ) ; } catch ( SQLException e ) { throw new RuntimeException ( e ) ; } }
|
Returns TRUE if another revision information is available .
|
4,309
|
public String getContext ( int wordsLeft , int wordsRight ) { final String text = home_cc . getText ( ) ; int temp ; int posLeft = pos . getStart ( ) ; temp = posLeft - 1 ; while ( posLeft != 0 && wordsLeft > 0 ) { while ( temp > 0 && text . charAt ( temp ) < 48 ) { temp -- ; } while ( temp > 0 && text . charAt ( temp ) >= 48 ) { temp -- ; } posLeft = ( temp > 0 ? temp + 1 : 0 ) ; wordsLeft -- ; } int posRight = pos . getEnd ( ) ; temp = posRight ; while ( posRight != text . length ( ) && wordsRight > 0 ) { while ( temp < text . length ( ) && text . charAt ( temp ) < 48 ) { temp ++ ; } while ( temp < text . length ( ) && text . charAt ( temp ) >= 48 ) { temp ++ ; } posRight = temp ; wordsRight -- ; } return text . substring ( posLeft , pos . getStart ( ) ) + text . substring ( pos . getEnd ( ) , posRight ) ; }
|
Returns the Number of Words left and right of the Link in the Bounds of the HomeElement of this Link .
|
4,310
|
protected void storeBuffer ( ) { if ( buffer != null && buffer . length ( ) > insertStatement . length ( ) ) { if ( ! insertStatement . isEmpty ( ) ) { this . buffer . append ( ";" ) ; } bufferList . add ( buffer ) ; } this . buffer = new StringBuilder ( ) ; this . buffer . append ( insertStatement ) ; }
|
Finalizes the query in the currently used buffer and creates a new one . The finalized query will be added to the list of queries .
|
4,311
|
public void enableSrcPosCalculation ( ) { calculateSrcPositions = true ; final int len = sb . length ( ) ; ib = new ArrayList < Integer > ( len ) ; for ( int i = 0 ; i < len ; i ++ ) ib . add ( i ) ; }
|
Enables the Calculation of Src Position . The base for these position will be the aktual not the initial String wich is uses as Base for the SpanManager .
|
4,312
|
public Set < Category > getSiblings ( ) { Set < Category > siblings = new HashSet < Category > ( ) ; for ( Category parent : this . getParents ( ) ) { siblings . addAll ( parent . getChildren ( ) ) ; } siblings . remove ( this ) ; return siblings ; }
|
Returns the siblings of this category .
|
4,313
|
public void writeDiff ( final Task < Diff > diff , final int start ) throws IOException { int size = diff . size ( ) ; Diff d ; String previousRevision = null , currentRevision = null ; this . writer . write ( WikipediaXMLKeys . KEY_START_PAGE . getKeyword ( ) + "\r\n" ) ; ArticleInformation header = diff . getHeader ( ) ; this . writer . write ( "\t" + WikipediaXMLKeys . KEY_START_TITLE . getKeyword ( ) ) ; this . writer . write ( header . getArticleName ( ) ) ; this . writer . write ( WikipediaXMLKeys . KEY_END_TITLE . getKeyword ( ) + "\r\n" ) ; this . writer . write ( "\t" + WikipediaXMLKeys . KEY_START_ID . getKeyword ( ) ) ; this . writer . write ( Integer . toString ( header . getArticleId ( ) ) ) ; this . writer . write ( WikipediaXMLKeys . KEY_END_ID . getKeyword ( ) + "\r\n" ) ; this . writer . write ( "\t<partCounter>" ) ; this . writer . write ( Integer . toString ( diff . getPartCounter ( ) ) ) ; this . writer . write ( "</partCounter>\r\n" ) ; for ( int i = start ; i < size ; i ++ ) { d = diff . get ( i ) ; currentRevision = d . buildRevision ( previousRevision ) ; this . writer . write ( "\t" + WikipediaXMLKeys . KEY_START_REVISION . getKeyword ( ) + "\r\n" ) ; this . writer . write ( "\t\t" + WikipediaXMLKeys . KEY_START_ID . getKeyword ( ) ) ; this . writer . write ( Integer . toString ( d . getRevisionID ( ) ) ) ; this . writer . write ( WikipediaXMLKeys . KEY_END_ID . getKeyword ( ) + "\r\n" ) ; this . writer . write ( "\t\t<revCount>" ) ; this . writer . write ( Integer . toString ( d . getRevisionCounter ( ) ) ) ; this . writer . write ( "</revCount>\r\n" ) ; this . writer . write ( "\t\t" + WikipediaXMLKeys . KEY_START_TIMESTAMP . getKeyword ( ) ) ; this . writer . write ( d . getTimeStamp ( ) . toString ( ) ) ; this . writer . write ( WikipediaXMLKeys . KEY_END_TIMESTAMP . getKeyword ( ) + "\r\n" ) ; this . writer . write ( "\t\t" + WikipediaXMLKeys . KEY_START_TEXT . getKeyword ( ) ) ; if ( currentRevision != null ) { this . writer . write ( currentRevision ) ; previousRevision = currentRevision ; } this . writer . write ( WikipediaXMLKeys . KEY_END_TEXT . getKeyword ( ) + "\r\n" ) ; this . writer . write ( "\t" + WikipediaXMLKeys . KEY_END_REVISION . getKeyword ( ) + "\r\n" ) ; } this . writer . write ( WikipediaXMLKeys . KEY_END_PAGE . getKeyword ( ) + "\r\n" ) ; this . writer . flush ( ) ; }
|
Writes a part of the diff task starting with the given element to the output using wikipedia xml notation .
|
4,314
|
public static boolean scan ( final char [ ] input ) { int surLow = 0xD800 ; int surHgh = 0xDFFF ; int end = input . length ; for ( int i = 0 ; i < end ; i ++ ) { if ( ( int ) input [ i ] >= surLow && input [ i ] <= surHgh ) { return true ; } } return false ; }
|
Returns whether a surrogate character was contained in the specified input .
|
4,315
|
public static char [ ] replace ( final char [ ] input ) { int surLow = 0xD800 ; int surHgh = 0xDFFF ; int end = input . length ; char [ ] output = new char [ end ] ; for ( int i = 0 ; i < end ; i ++ ) { if ( ( int ) input [ i ] >= surLow && input [ i ] <= surHgh ) { output [ i ] = '?' ; } else { output [ i ] = input [ i ] ; } } return output ; }
|
Replaces all surrogates characters with ? .
|
4,316
|
public static void logArticleRead ( final Logger logger , final Task < Revision > article , final long time , final long position ) { logger . logMessage ( Level . INFO , "Read article\t" + Time . toClock ( time ) + "\t" + article . toString ( ) + "\t" + position ) ; }
|
Logs the reading of an revision task .
|
4,317
|
public static void logErrorRetrieveArchive ( final Logger logger , final ArchiveDescription archive , final Error e ) { logger . logError ( Level . ERROR , "Error while accessing archive " + archive . toString ( ) , e ) ; }
|
Logs the occurance of an error while retrieving the input file .
|
4,318
|
public static void logExceptionRetrieveArchive ( final Logger logger , final ArchiveDescription archive , final Exception e ) { logger . logException ( Level . ERROR , "Exception while accessing archive " + archive . toString ( ) , e ) ; }
|
Logs the occurance of an exception while retrieving the input file .
|
4,319
|
public static void logNoMoreArticles ( final Logger logger , final ArchiveDescription archive ) { logger . logMessage ( Level . INFO , "Archive " + archive . toString ( ) + " contains no more articles" ) ; }
|
Logs that no more articles are available .
|
4,320
|
public static void logReadTaskException ( final Logger logger , final Task < Revision > task , final Exception e ) { if ( task != null ) { logger . logException ( Level . ERROR , "Error while reading a task: " + task . toString ( ) , e ) ; } else { logger . logException ( Level . ERROR , "Error while reading an unknown task" , e ) ; } }
|
Logs an occurance of an exception while reading a task .
|
4,321
|
public static void logStatus ( final Logger logger , final ArticleReaderInterface articleReader , final long startTime , final long sleepingTime , final long workingTime ) { String message = "Consumer-Status-Report [" + Time . toClock ( System . currentTimeMillis ( ) - startTime ) + "]" ; if ( articleReader != null ) { message += "\tPOSITION <" + articleReader . getBytePosition ( ) + ">" ; } message += "\tEFFICIENCY\t " + MathUtilities . percentPlus ( workingTime , sleepingTime ) + "\tWORK [" + Time . toClock ( workingTime ) + "]" + "\tSLEEP [" + Time . toClock ( sleepingTime ) + "]" ; logger . logMessage ( Level . DEBUG , message ) ; }
|
Logs the status of the article consumer .
|
4,322
|
public static void logTaskReaderException ( final Logger logger , final ArticleReaderException e ) { logger . logException ( Level . ERROR , "TaskReaderException" , e ) ; }
|
Logs the occurance of an ArticleReaderException .
|
4,323
|
public static void logDiffProcessed ( final Logger logger , final Task < Diff > diff , final long time ) { logger . logMessage ( Level . INFO , "Generated Entry\t" + Time . toClock ( time ) + "\t" + diff . toString ( ) ) ; }
|
Logs the processing of a diff task .
|
4,324
|
public static void logFileCreation ( final Logger logger , final String path ) { logger . logMessage ( Level . INFO , "New File created:\t" + path ) ; }
|
Logs the creation of an output file .
|
4,325
|
public static void logReadTaskOutOfMemoryError ( final Logger logger , final Task < Diff > task , final OutOfMemoryError e ) { if ( task != null ) { logger . logError ( Level . WARN , "Error while reading a task: " + task . toString ( ) , e ) ; } else { logger . logError ( Level . WARN , "Error while reading an unknown task" , e ) ; } }
|
Logs the occurrence of an OutOfMemoryError while reading a task .
|
4,326
|
public static void logSQLConsumerException ( final Logger logger , final SQLConsumerException e ) { logger . logException ( Level . ERROR , "SQLConsumerException" , e ) ; }
|
Logs the occurrence of an SqlConsumerException .
|
4,327
|
public static void logStatus ( final Logger logger , final long time , final int articleConsumer , final int diffConsumer , final int sqlConsumer , final boolean archiveState , final boolean articleState , final boolean diffState ) { logger . logMessage ( Level . INFO , "\r\nDiffTool-Status-Report [" + Time . toClock ( time ) + "]" + "\r\nConsumerProducer \t[" + articleConsumer + " | " + diffConsumer + " | " + sqlConsumer + "]" + "\r\nArchiveProducer\t" + archiveState + "\r\nArticleProducer\t" + articleState + "\r\nDiffProducer \t" + diffState + "\r\n" ) ; }
|
Logs the status of the diff tool .
|
4,328
|
public static void logShutdown ( final Logger logger , final long endTime ) { logger . logMessage ( Level . INFO , "DiffTool initiates SHUTDOWN\t" + Time . toClock ( endTime ) ) ; }
|
Logs the shutdown of the logger .
|
4,329
|
public void writeEndPage ( ) throws IOException { writer . openElement ( "document" ) ; writer . textElement ( "id" , Integer . toString ( _page . Id ) ) ; writer . textElement ( "group" , "0" ) ; writer . textElement ( "timestamp" , formatTimestamp ( _rev . Timestamp ) ) ; writer . textElement ( "title" , _page . Title . toString ( ) ) ; writer . textElement ( "body" , _rev . Text ) ; writer . closeElement ( ) ; _rev = null ; _page = null ; }
|
FIXME What s the group number here do? FIXME preprocess the text to strip some formatting?
|
4,330
|
private static boolean checkArgs ( String [ ] args ) { boolean result = ( args . length > 0 ) ; if ( ! result ) { System . out . println ( "Usage: java -jar JWPLTimeMachine.jar <config-file>" ) ; } return result ; }
|
Checks given arguments
|
4,331
|
public Title getTitle ( int pageId ) throws WikiApiException { Session session = this . __getHibernateSession ( ) ; session . beginTransaction ( ) ; Object returnValue = session . createNativeQuery ( "select p.name from PageMapLine as p where p.pageId= :pId" ) . setParameter ( "pId" , pageId , IntegerType . INSTANCE ) . uniqueResult ( ) ; session . getTransaction ( ) . commit ( ) ; String title = ( String ) returnValue ; if ( title == null ) { throw new WikiPageNotFoundException ( ) ; } return new Title ( title ) ; }
|
Gets the title for a given pageId .
|
4,332
|
public Page getArticleForDiscussionPage ( Page discussionPage ) throws WikiApiException { if ( discussionPage . isDiscussion ( ) ) { String title = discussionPage . getTitle ( ) . getPlainTitle ( ) . replaceAll ( WikiConstants . DISCUSSION_PREFIX , "" ) ; if ( title . contains ( "/" ) ) { title = title . split ( "/" ) [ 0 ] ; } return getPage ( title ) ; } else { return discussionPage ; } }
|
Returns the article page for a given discussion page .
|
4,333
|
public Page getDiscussionPage ( Page articlePage ) throws WikiApiException { String articleTitle = articlePage . getTitle ( ) . toString ( ) ; if ( articleTitle . startsWith ( WikiConstants . DISCUSSION_PREFIX ) ) { return articlePage ; } else { return new Page ( this , WikiConstants . DISCUSSION_PREFIX + articleTitle ) ; } }
|
Gets the discussion page for the given article page The provided page must not be a discussion page
|
4,334
|
protected Map < Page , Double > getSimilarPages ( String pPattern , int pSize ) throws WikiApiException { Title title = new Title ( pPattern ) ; String pattern = title . getWikiStyleTitle ( ) ; Map < Page , Double > pageMap = new HashMap < Page , Double > ( ) ; Map < Integer , Double > distanceMap = new HashMap < Integer , Double > ( ) ; Session session = this . __getHibernateSession ( ) ; session . beginTransaction ( ) ; Iterator results = session . createQuery ( "select pml.pageID, pml.name from PageMapLine as pml" ) . list ( ) . iterator ( ) ; while ( results . hasNext ( ) ) { Object [ ] row = ( Object [ ] ) results . next ( ) ; int pageID = ( Integer ) row [ 0 ] ; String pageName = ( String ) row [ 1 ] ; double distance = new LevenshteinStringDistance ( ) . distance ( pageName , pattern ) ; distanceMap . put ( pageID , distance ) ; if ( distanceMap . size ( ) > pSize ) { Set < Map . Entry < Integer , Double > > valueSortedSet = new TreeSet < Map . Entry < Integer , Double > > ( new ValueComparator ( ) ) ; valueSortedSet . addAll ( distanceMap . entrySet ( ) ) ; Iterator it = valueSortedSet . iterator ( ) ; if ( it . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) it . next ( ) ; distanceMap . remove ( entry . getKey ( ) ) ; } } } session . getTransaction ( ) . commit ( ) ; for ( int pageID : distanceMap . keySet ( ) ) { Page page = null ; try { page = this . getPage ( pageID ) ; } catch ( WikiPageNotFoundException e ) { logger . error ( "Page with pageID " + pageID + " could not be found. Fatal error. Terminating." ) ; e . printStackTrace ( ) ; System . exit ( 1 ) ; } pageMap . put ( page , distanceMap . get ( pageID ) ) ; } return pageMap ; }
|
Gets the pages or redirects with a name similar to the pattern . Calling this method is quite costly as similarity is computed for all names .
|
4,335
|
public Category getCategory ( int pageId ) { long hibernateId = __getCategoryHibernateId ( pageId ) ; if ( hibernateId == - 1 ) { return null ; } try { Category cat = new Category ( this , hibernateId ) ; return cat ; } catch ( WikiPageNotFoundException e ) { return null ; } }
|
Gets the category for a given pageId .
|
4,336
|
protected Set < Integer > __getCategories ( ) { Session session = this . __getHibernateSession ( ) ; session . beginTransaction ( ) ; List < Integer > idList = session . createQuery ( "select cat.pageId from Category as cat" , Integer . class ) . list ( ) ; Set < Integer > categorySet = new HashSet < Integer > ( idList ) ; session . getTransaction ( ) . commit ( ) ; return categorySet ; }
|
Protected method that is much faster than the public version but exposes too much implementation details . Get a set with all category pageIDs . Returning all category objects is much too expensive .
|
4,337
|
public boolean existsPage ( String title ) { if ( title == null || title . length ( ) == 0 ) { return false ; } Title t ; try { t = new Title ( title ) ; } catch ( WikiTitleParsingException e ) { return false ; } String encodedTitle = t . getWikiStyleTitle ( ) ; Session session = this . __getHibernateSession ( ) ; session . beginTransaction ( ) ; String query = "select p.id from PageMapLine as p where p.name = :pName" ; if ( dbConfig . supportsCollation ( ) ) { query += SQL_COLLATION ; } Object returnValue = session . createNativeQuery ( query ) . setParameter ( "pName" , encodedTitle , StringType . INSTANCE ) . uniqueResult ( ) ; session . getTransaction ( ) . commit ( ) ; return returnValue != null ; }
|
Tests whether a page or redirect with the given title exists . Trying to retrieve a page that does not exist in Wikipedia throws an exception . You may catch the exception or use this test depending on your task .
|
4,338
|
public boolean existsPage ( int pageID ) { if ( pageID < 0 ) { return false ; } Session session = this . __getHibernateSession ( ) ; session . beginTransaction ( ) ; List returnList = session . createNativeQuery ( "select p.id from PageMapLine as p where p.pageID = :pageId" ) . setParameter ( "pageId" , pageID , IntegerType . INSTANCE ) . list ( ) ; session . getTransaction ( ) . commit ( ) ; return returnList . size ( ) != 0 ; }
|
Tests whether a page with the given pageID exists . Trying to retrieve a pageID that does not exist in Wikipedia throws an exception .
|
4,339
|
protected long __getPageHibernateId ( int pageID ) { long hibernateID = - 1 ; if ( idMapPages . containsKey ( pageID ) ) { return idMapPages . get ( pageID ) ; } Session session = this . __getHibernateSession ( ) ; session . beginTransaction ( ) ; Object retObjectPage = session . createQuery ( "select page.id from Page as page where page.pageId = :pageId" ) . setParameter ( "pageId" , pageID , IntegerType . INSTANCE ) . uniqueResult ( ) ; session . getTransaction ( ) . commit ( ) ; if ( retObjectPage != null ) { hibernateID = ( Long ) retObjectPage ; idMapPages . put ( pageID , hibernateID ) ; return hibernateID ; } return hibernateID ; }
|
Get the hibernate ID to a given pageID of a page . We need different methods for pages and categories here as a page and a category can have the same ID .
|
4,340
|
public String getWikipediaId ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( this . getDatabaseConfiguration ( ) . getHost ( ) ) ; sb . append ( "_" ) ; sb . append ( this . getDatabaseConfiguration ( ) . getDatabase ( ) ) ; sb . append ( "_" ) ; sb . append ( this . getDatabaseConfiguration ( ) . getLanguage ( ) ) ; return sb . toString ( ) ; }
|
The ID consists of the host the database and the language . This should be unique in most cases .
|
4,341
|
private byte [ ] encode ( final RevisionCodecData codecData , final Diff diff ) throws UnsupportedEncodingException , EncodingException { this . data = new BitWriter ( codecData . totalSizeInBits ( ) ) ; encodeCodecData ( codecData ) ; DiffPart part ; Iterator < DiffPart > partIt = diff . iterator ( ) ; while ( partIt . hasNext ( ) ) { part = partIt . next ( ) ; switch ( part . getAction ( ) ) { case FULL_REVISION_UNCOMPRESSED : encodeFullRevisionUncompressed ( part ) ; break ; case INSERT : encodeInsert ( part ) ; break ; case DELETE : encodeDelete ( part ) ; break ; case REPLACE : encodeReplace ( part ) ; break ; case CUT : encodeCut ( part ) ; break ; case PASTE : encodePaste ( part ) ; break ; default : throw new RuntimeException ( ) ; } } return data . toByteArray ( ) ; }
|
Creates the binary encoding of the diff while using the codec information .
|
4,342
|
private void encodeCodecData ( final RevisionCodecData codecData ) throws EncodingException { this . codecData = codecData ; data . writeBit ( 0 ) ; data . writeBit ( 0 ) ; data . writeBit ( 0 ) ; this . data . writeValue ( 5 , codecData . getBlocksizeS ( ) ) ; this . data . writeValue ( 5 , codecData . getBlocksizeE ( ) ) ; this . data . writeValue ( 5 , codecData . getBlocksizeB ( ) ) ; this . data . writeValue ( 5 , codecData . getBlocksizeL ( ) ) ; data . writeFillBits ( ) ; }
|
Encodes the codecData .
|
4,343
|
private void encodeCut ( final DiffPart part ) throws EncodingException { data . writeBit ( 1 ) ; data . writeBit ( 0 ) ; data . writeBit ( 1 ) ; data . writeValue ( codecData . getBlocksizeS ( ) , part . getStart ( ) ) ; data . writeValue ( codecData . getBlocksizeE ( ) , part . getLength ( ) ) ; data . writeValue ( codecData . getBlocksizeB ( ) , Integer . parseInt ( part . getText ( ) ) ) ; data . writeFillBits ( ) ; }
|
Encodes a Cut operation .
|
4,344
|
private void encodeDelete ( final DiffPart part ) throws EncodingException { data . writeBit ( 0 ) ; data . writeBit ( 1 ) ; data . writeBit ( 1 ) ; data . writeValue ( codecData . getBlocksizeS ( ) , part . getStart ( ) ) ; data . writeValue ( codecData . getBlocksizeE ( ) , part . getLength ( ) ) ; data . writeFillBits ( ) ; }
|
Encodes a Delete operation .
|
4,345
|
private void encodeFullRevisionUncompressed ( final DiffPart part ) throws UnsupportedEncodingException , EncodingException { data . writeBit ( 0 ) ; data . writeBit ( 0 ) ; data . writeBit ( 1 ) ; String text = part . getText ( ) ; byte [ ] bText = text . getBytes ( WIKIPEDIA_ENCODING ) ; data . writeValue ( codecData . getBlocksizeL ( ) , bText . length ) ; data . write ( bText ) ; }
|
Encodes a FullRevision operation .
|
4,346
|
private void encodePaste ( final DiffPart part ) throws EncodingException { data . writeBit ( 1 ) ; data . writeBit ( 1 ) ; data . writeBit ( 0 ) ; data . writeValue ( codecData . getBlocksizeS ( ) , part . getStart ( ) ) ; data . writeValue ( codecData . getBlocksizeB ( ) , Integer . parseInt ( part . getText ( ) ) ) ; data . writeFillBits ( ) ; }
|
Encodes a Paste operation .
|
4,347
|
public void readDump ( ) throws IOException { try { SAXParserFactory factory = SAXParserFactory . newInstance ( ) ; factory . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , false ) ; SAXParser parser = factory . newSAXParser ( ) ; parser . parse ( input , this ) ; } catch ( ParserConfigurationException e ) { throw ( IOException ) new IOException ( e . getMessage ( ) ) . initCause ( e ) ; } catch ( SAXException e ) { throw ( IOException ) new IOException ( e . getMessage ( ) ) . initCause ( e ) ; } writer . close ( ) ; }
|
Reads through the entire XML dump on the input stream sending events to the DumpWriter as it goes . May throw exceptions on invalid input or due to problems with the output .
|
4,348
|
public int compareTo ( final ChronoIndexData info ) { long value ; if ( chronoSort ) { value = this . time - info . time ; } else { value = this . revisionCounter - info . revisionCounter ; } if ( value == 0 ) { return 0 ; } else if ( value > 0 ) { return 1 ; } else { return - 1 ; } }
|
Compares this ChronoInfo to the given info .
|
4,349
|
public Iterable < Page > getPagesContainingTemplateNames ( List < String > templateNames ) throws WikiApiException { return getFilteredPages ( templateNames , true ) ; }
|
Return an iterable containing all pages that contain a template the name of which equals any of the given Strings .
|
4,350
|
public Iterable < Page > getPagesNotContainingTemplateNames ( List < String > templateNames ) throws WikiApiException { return getFilteredPages ( templateNames , false ) ; }
|
Return an iterable containing all pages that do NOT contain a template the name of which equals of the given Strings .
|
4,351
|
public List < Integer > getRevisionsWithFirstTemplateAppearance ( String templateName ) throws WikiApiException { System . err . println ( "Note: This function call demands parsing several revision for each page. A method using the revision-template index is currently under construction." ) ; templateName = templateName . trim ( ) . replaceAll ( " " , "_" ) ; List < Integer > revisionIds = new LinkedList < Integer > ( ) ; List < Integer > pageIds = getPageIdsContainingTemplateNames ( Arrays . asList ( new String [ ] { templateName } ) ) ; if ( pageIds . size ( ) == 0 ) { return revisionIds ; } if ( revApi == null ) { revApi = new RevisionApi ( wiki . getDatabaseConfiguration ( ) ) ; } if ( parser == null ) { MediaWikiParserFactory pf = new MediaWikiParserFactory ( wiki . getDatabaseConfiguration ( ) . getLanguage ( ) ) ; pf . setTemplateParserClass ( ShowTemplateNamesAndParameters . class ) ; parser = pf . createParser ( ) ; } for ( int id : pageIds ) { List < Timestamp > tsList = revApi . getRevisionTimestamps ( id ) ; Collections . sort ( tsList , new Comparator < Timestamp > ( ) { public int compare ( Timestamp ts1 , Timestamp ts2 ) { return ts2 . compareTo ( ts1 ) ; } } ) ; Revision prevRev = null ; tsloop : for ( Timestamp ts : tsList ) { Revision rev = revApi . getRevision ( id , ts ) ; if ( prevRev == null ) { prevRev = rev ; } ParsedPage pp = parser . parse ( rev . getRevisionText ( ) ) ; boolean containsTpl = false ; tplLoop : for ( Template tpl : pp . getTemplates ( ) ) { if ( tpl . getName ( ) . equalsIgnoreCase ( templateName ) ) { containsTpl = true ; break tplLoop ; } } if ( ! containsTpl ) { revisionIds . add ( prevRev . getRevisionID ( ) ) ; break tsloop ; } prevRev = rev ; } } return revisionIds ; }
|
This method first creates a list of pages containing templates that equal any of the provided Strings . It then returns a list of revision ids of the revisions in which the respective templates first appeared .
|
4,352
|
public List < Integer > getIdsOfPagesThatEverContainedTemplateNames ( List < String > templateNames ) throws WikiApiException { if ( revApi == null ) { revApi = new RevisionApi ( wiki . getDatabaseConfiguration ( ) ) ; } Set < Integer > pageIdSet = new HashSet < Integer > ( ) ; List < Integer > revsWithTemplate = getRevisionIdsContainingTemplateNames ( templateNames ) ; for ( int revId : revsWithTemplate ) { pageIdSet . add ( revApi . getPageIdForRevisionId ( revId ) ) ; } List < Integer > pageIds = new LinkedList < Integer > ( ) ; pageIds . addAll ( pageIdSet ) ; return pageIds ; }
|
Returns the ids of all pages that ever contained any of the given template names in the history of their existence .
|
4,353
|
public List < Integer > getIdsOfPagesThatEverContainedTemplateFragments ( List < String > templateFragments ) throws WikiApiException { if ( revApi == null ) { revApi = new RevisionApi ( wiki . getDatabaseConfiguration ( ) ) ; } Set < Integer > pageIdSet = new HashSet < Integer > ( ) ; List < Integer > revsWithTemplate = getRevisionIdsContainingTemplateFragments ( templateFragments ) ; for ( int revId : revsWithTemplate ) { pageIdSet . add ( revApi . getPageIdForRevisionId ( revId ) ) ; } List < Integer > pageIds = new LinkedList < Integer > ( ) ; pageIds . addAll ( pageIdSet ) ; return pageIds ; }
|
Returns the ids of all pages that ever contained any template that started with any of the given template fragments
|
4,354
|
public List < Integer > getPageIdsContainingTemplateNames ( List < String > templateNames ) throws WikiApiException { return getFilteredPageIds ( templateNames , true ) ; }
|
Returns a list containing the ids of all pages that contain a template the name of which equals any of the given Strings .
|
4,355
|
public List < Integer > getPageIdsNotContainingTemplateNames ( List < String > templateNames ) throws WikiApiException { return getFilteredPageIds ( templateNames , false ) ; }
|
Returns a list containing the ids of all pages that do not contain a template the name of which equals any of the given Strings .
|
4,356
|
public List < Integer > getRevisionIdsContainingTemplateNames ( List < String > templateNames ) throws WikiApiException { return getFilteredRevisionIds ( templateNames , true ) ; }
|
Returns a list containing the ids of all revisions that contain a template the name of which equals any of the given Strings .
|
4,357
|
public List < Integer > getRevisionIdsNotContainingTemplateNames ( List < String > templateNames ) throws WikiApiException { return getFilteredRevisionIds ( templateNames , false ) ; }
|
Returns a list containing the ids of all revisions that do not contain a template the name of which equals any of the given Strings .
|
4,358
|
public List < String > getTemplateNamesFromRevision ( int revid ) throws WikiApiException { if ( revid < 1 ) { throw new WikiApiException ( "Revision ID must be > 0" ) ; } try { PreparedStatement statement = null ; ResultSet result = null ; List < String > templateNames = new LinkedList < String > ( ) ; try { statement = connection . prepareStatement ( "SELECT tpl.templateName FROM " + GeneratorConstants . TABLE_TPLID_TPLNAME + " AS tpl, " + GeneratorConstants . TABLE_TPLID_REVISIONID + " AS p WHERE tpl.templateId = p.templateId AND p.revisionId = ?" ) ; statement . setInt ( 1 , revid ) ; result = execute ( statement ) ; if ( result == null ) { return templateNames ; } while ( result . next ( ) ) { templateNames . add ( result . getString ( 1 ) . toLowerCase ( ) ) ; } } finally { if ( statement != null ) { statement . close ( ) ; } if ( result != null ) { result . close ( ) ; } } return templateNames ; } catch ( Exception e ) { throw new WikiApiException ( e ) ; } }
|
Returns the names of all templates contained in the specified revision .
|
4,359
|
public boolean revisionContainsTemplateFragment ( int revId , String templateFragment ) throws WikiApiException { List < String > tplList = getTemplateNamesFromRevision ( revId ) ; for ( String tpl : tplList ) { if ( tpl . toLowerCase ( ) . startsWith ( templateFragment . toLowerCase ( ) ) ) { return true ; } } return false ; }
|
Determines whether a given revision contains a template starting witht the given fragment
|
4,360
|
public boolean tableExists ( String table ) throws SQLException { PreparedStatement statement = null ; ResultSet result = null ; try { statement = this . connection . prepareStatement ( "SHOW TABLES;" ) ; result = execute ( statement ) ; if ( result == null ) { return false ; } boolean found = false ; while ( result . next ( ) ) { if ( table . equalsIgnoreCase ( result . getString ( 1 ) ) ) { found = true ; } } return found ; } finally { if ( statement != null ) { statement . close ( ) ; } if ( result != null ) { result . close ( ) ; } } }
|
Checks if a specific table exists
|
4,361
|
public void add ( final ChronoStorageBlock block ) { int revCount = block . getRevisionCounter ( ) ; this . size += block . length ( ) ; if ( first == null ) { first = block ; } else { ChronoStorageBlock previous = null , current = first ; do { if ( revCount < current . getRevisionCounter ( ) ) { block . setCounterPrev ( previous ) ; block . setCounterNext ( current ) ; if ( previous != null ) { previous . setCounterNext ( block ) ; } current . setCounterPrev ( block ) ; if ( current == this . first ) { this . first = block ; } return ; } previous = current ; current = current . getCounterNext ( ) ; } while ( current != null ) ; previous . setCounterNext ( block ) ; block . setCounterPrev ( previous ) ; } }
|
Adds a ChonoStorageBlock to this chrono full revision object .
|
4,362
|
public Revision getNearest ( final int revisionCounter ) { if ( first != null ) { ChronoStorageBlock previous = null , current = first ; while ( current != null && current . getRevisionCounter ( ) <= revisionCounter ) { previous = current ; current = current . getCounterNext ( ) ; } return previous . getRev ( ) ; } return null ; }
|
Returns the nearest available revision to the specified revision counter .
|
4,363
|
public long clean ( final int currentRevisionIndex , final int revisionIndex ) { if ( first == null ) { return 0 ; } else if ( this . set . isEmpty ( ) ) { this . first = null ; this . size = 0 ; return 0 ; } ChronoStorageBlock next , prev , current = first ; boolean remove ; do { remove = false ; if ( current . isDelivered ( ) ) { next = current . getCounterNext ( ) ; if ( next != null ) { if ( current . getRevisionCounter ( ) + 1 == next . getRevisionCounter ( ) ) { remove = true ; } } } else if ( current . getIndexNext ( ) == null && current . getIndexPrev ( ) == null ) { remove = ( current . getRevisionIndex ( ) < currentRevisionIndex ) || ( current . getRevisionIndex ( ) == revisionIndex ) ; } if ( remove ) { prev = current . getCounterPrev ( ) ; next = current . getCounterNext ( ) ; current . setCounterNext ( null ) ; current . setCounterPrev ( null ) ; if ( prev != null ) { prev . setCounterNext ( next ) ; } if ( next != null ) { next . setCounterPrev ( prev ) ; } if ( current == first ) { this . first = next ; } this . size -= current . length ( ) ; current = next ; } if ( current != null ) { current = current . getCounterNext ( ) ; } } while ( current != null ) ; return this . size ; }
|
Reduces the storage space .
|
4,364
|
public static HashSet < String > createSetFromProperty ( String property ) { HashSet < String > properties = new HashSet < String > ( ) ; if ( property != null && ! property . equals ( "null" ) ) { Pattern params = Pattern . compile ( "([\\w]+)[;]*" ) ; Matcher matcher = params . matcher ( property . trim ( ) ) ; while ( matcher . find ( ) ) { properties . add ( matcher . group ( 1 ) ) ; } } return properties ; }
|
Parses property string into HashSet
|
4,365
|
private boolean notAllowedStart ( String startTag ) { errorState = errorState && startElements . containsKey ( startTag ) && forbiddenIdStartElements . containsKey ( startTag ) ; return errorState ; }
|
If error with wrong id tag occurs the errorState flag will be set . In this case some start tags have to be ignored .
|
4,366
|
private boolean notAllowedEnd ( String endTag ) { errorState = errorState && endElements . containsKey ( endTag ) && forbiddenIdEndElements . containsKey ( endTag ) ; return errorState ; }
|
If error with wrong id tag occurs the errorState flag will be set . In this case some end tags have to be ignored .
|
4,367
|
private List < String > sentenceSplit ( String str ) { BreakIterator iterator = BreakIterator . getSentenceInstance ( Locale . US ) ; iterator . setText ( str ) ; int start = iterator . first ( ) ; List < String > sentences = new ArrayList < String > ( ) ; for ( int end = iterator . next ( ) ; end != BreakIterator . DONE ; start = end , end = iterator . next ( ) ) { sentences . add ( str . substring ( start , end ) . trim ( ) ) ; } return sentences ; }
|
Splits a String into sentences using the BreakIterator with US locale
|
4,368
|
private String listToString ( List < String > stringList ) { StringBuilder concat = new StringBuilder ( ) ; for ( String str : stringList ) { concat . append ( str ) ; concat . append ( System . getProperty ( "line.separator" ) ) ; } return concat . toString ( ) ; }
|
Concatenates a list of Strings to one line - separated String
|
4,369
|
private String normalize ( String str ) { str = StringUtils . trimToEmpty ( str ) ; str = StringUtils . normalizeSpace ( str ) ; str = str . replaceAll ( "\\s+(?=[.!,\\?;:])" , "" ) ; return str ; }
|
Normalizes the Strings in the TextPair . This mainly deals with whitespace - issues . Other normalizations can be included .
|
4,370
|
public Revision getDiscussionRevisionForArticleRevision ( int revisionId ) throws WikiApiException , WikiPageNotFoundException { Revision rev = revApi . getRevision ( revisionId ) ; Timestamp revTime = rev . getTimeStamp ( ) ; Page discussion = wiki . getDiscussionPage ( rev . getArticleID ( ) ) ; List < Timestamp > discussionTs = revApi . getRevisionTimestamps ( discussion . getPageId ( ) ) ; Collections . sort ( discussionTs , new Comparator < Timestamp > ( ) { public int compare ( Timestamp ts1 , Timestamp ts2 ) { return ts2 . compareTo ( ts1 ) ; } } ) ; for ( Timestamp curDiscTime : discussionTs ) { if ( curDiscTime == revTime || curDiscTime . before ( revTime ) ) { return revApi . getRevision ( discussion . getPageId ( ) , curDiscTime ) ; } } throw new WikiPageNotFoundException ( "Not discussion page was available at the time of the given article revision" ) ; }
|
For a given article revision the method returns the revision of the article discussion page which was current at the time the revision was created .
|
4,371
|
public List < Revision > getDiscussionArchiveRevisionsForArticleRevision ( int revisionId ) throws WikiApiException , WikiPageNotFoundException { List < Revision > result = new LinkedList < Revision > ( ) ; Revision rev = revApi . getRevision ( revisionId ) ; Timestamp revTime = rev . getTimeStamp ( ) ; Iterable < Page > discArchives = wiki . getDiscussionArchives ( rev . getArticleID ( ) ) ; for ( Page discArchive : discArchives ) { List < Timestamp > discussionTs = revApi . getRevisionTimestamps ( discArchive . getPageId ( ) ) ; Collections . sort ( discussionTs , new Comparator < Timestamp > ( ) { public int compare ( Timestamp ts1 , Timestamp ts2 ) { return ts2 . compareTo ( ts1 ) ; } } ) ; for ( Timestamp curDiscTime : discussionTs ) { if ( curDiscTime == revTime || curDiscTime . before ( revTime ) ) { result . add ( revApi . getRevision ( discArchive . getPageId ( ) , curDiscTime ) ) ; break ; } } } return result ; }
|
For a given article revision the method returns the revisions of the archived article discussion pages which were available at the time of the article revision
|
4,372
|
public static String getRedirectDestination ( String pageText ) { String redirectString = null ; try { String regex = "\\[\\[\\s*(.+?)\\s*]]" ; Pattern pattern = Pattern . compile ( regex ) ; Matcher matcher = pattern . matcher ( pageText ) ; if ( matcher . find ( ) ) { redirectString = matcher . group ( 1 ) ; } if ( redirectString == null ) { return null ; } String [ ] anchorSplitValues = redirectString . split ( "#" ) ; redirectString = anchorSplitValues [ 0 ] ; redirectString = redirectString . trim ( ) ; String [ ] directSplitValues = redirectString . split ( "\\|" ) ; redirectString = directSplitValues [ 0 ] ; redirectString = redirectString . trim ( ) ; redirectString = redirectString . trim ( ) ; String regexNamespace = ":([^\\s].+)" ; Pattern patternNamespace = Pattern . compile ( regexNamespace ) ; Matcher matcherNamespace = patternNamespace . matcher ( redirectString ) ; if ( matcherNamespace . find ( ) ) { redirectString = matcherNamespace . group ( 1 ) ; } redirectString = redirectString . replace ( " " , "_" ) ; if ( redirectString . length ( ) > 0 ) { redirectString = redirectString . substring ( 0 , 1 ) . toUpperCase ( ) + redirectString . substring ( 1 , redirectString . length ( ) ) ; } } catch ( Exception e ) { redirectString = null ; logger . debug ( "Error in Redirects ignored" ) ; } return redirectString ; }
|
Return the redirect destination of according to wikimedia syntax .
|
4,373
|
public void add ( final ConfigItem item ) { failed = failed || item . getType ( ) == ConfigItemTypes . ERROR ; this . list . add ( item ) ; }
|
Adds a configuration item to the list .
|
4,374
|
public Object getValueAt ( final int row , final int column ) { ConfigItem item = this . list . get ( row ) ; switch ( column ) { case 0 : return item . getType ( ) ; case 1 : return item . getKey ( ) ; case 2 : return item . getMessage ( ) ; } return null ; }
|
Returns the value at the specified column of the specified row .
|
4,375
|
private String generatePageSQLStatement ( boolean tableExists , Map < String , Set < Integer > > dataSourceToUse ) { StringBuffer output = new StringBuffer ( ) ; output . append ( "CREATE TABLE IF NOT EXISTS " + GeneratorConstants . TABLE_TPLID_PAGEID + " (" + "templateId INTEGER UNSIGNED NOT NULL," + "pageId INTEGER UNSIGNED NOT NULL, UNIQUE(templateId, pageId));\r\n" ) ; output . append ( this . generateSQLStatementForDataInTable ( dataSourceToUse , GeneratorConstants . TABLE_TPLID_PAGEID ) ) ; if ( ! tableExists ) { output . append ( "CREATE INDEX pageIdx ON " + GeneratorConstants . TABLE_TPLID_PAGEID + "(pageId);" ) ; output . append ( "\r\n" ) ; } return output . toString ( ) ; }
|
Generate sql statement for table template id - > page id
|
4,376
|
private String generateTemplateIdSQLStatement ( boolean tableExists ) { StringBuffer output = new StringBuffer ( ) ; output . append ( "CREATE TABLE IF NOT EXISTS " + GeneratorConstants . TABLE_TPLID_TPLNAME + " (" + "templateId INTEGER NOT NULL AUTO_INCREMENT," + "templateName MEDIUMTEXT NOT NULL, " + "PRIMARY KEY(templateId)); \r\n" ) ; if ( ! tableExists ) { output . append ( "CREATE INDEX tplIdx ON " + GeneratorConstants . TABLE_TPLID_TPLNAME + "(templateId);" ) ; output . append ( "\r\n" ) ; } return output . toString ( ) ; }
|
Generate sql statement for table template id - > template name
|
4,377
|
private String generateRevisionSQLStatement ( boolean tableExists , Map < String , Set < Integer > > dataSourceToUse ) { StringBuffer output = new StringBuffer ( ) ; output . append ( "CREATE TABLE IF NOT EXISTS " + GeneratorConstants . TABLE_TPLID_REVISIONID + " (" + "templateId INTEGER UNSIGNED NOT NULL," + "revisionId INTEGER UNSIGNED NOT NULL, UNIQUE(templateId, revisionId));\r\n" ) ; output . append ( this . generateSQLStatementForDataInTable ( dataSourceToUse , GeneratorConstants . TABLE_TPLID_REVISIONID ) ) ; if ( ! tableExists ) { output . append ( "CREATE INDEX revisionIdx ON " + GeneratorConstants . TABLE_TPLID_REVISIONID + "(revisionID);" ) ; output . append ( "\r\n" ) ; } return output . toString ( ) ; }
|
Generate sql statement for table template id - > revision id
|
4,378
|
void writeSQL ( boolean revTableExists , boolean pageTableExists , GeneratorMode mode ) { try ( Writer writer = new BufferedWriter ( new OutputStreamWriter ( new BufferedOutputStream ( new FileOutputStream ( outputPath ) ) , charset ) ) ) { StringBuilder dataToDump = new StringBuilder ( ) ; dataToDump . append ( generateTemplateIdSQLStatement ( this . tableExists ) ) ; if ( mode . active_for_pages ) { dataToDump . append ( generatePageSQLStatement ( pageTableExists , mode . templateNameToPageId ) ) ; } if ( mode . active_for_revisions ) { dataToDump . append ( generateRevisionSQLStatement ( revTableExists , mode . templateNameToRevId ) ) ; } writer . write ( dataToDump . toString ( ) ) ; } catch ( IOException e ) { logger . error ( "Error writing SQL file: {}" , e . getMessage ( ) , e ) ; } }
|
Generate and write sql statements to output file
|
4,379
|
public static ModifyType detectModifyType ( SQLiteModelMethod method , JQLType jqlType ) { SQLiteDaoDefinition daoDefinition = method . getParent ( ) ; SQLiteEntity entity = method . getEntity ( ) ; ModifyType updateResultType = null ; int count = 0 ; for ( Pair < String , TypeName > param : method . getParameters ( ) ) { if ( method . isThisDynamicWhereConditionsName ( param . value0 ) ) { continue ; } if ( TypeUtility . isEquals ( param . value1 , typeName ( entity . getElement ( ) ) ) ) { count ++ ; } } if ( count == 0 ) { updateResultType = jqlType == JQLType . UPDATE ? ModifyType . UPDATE_RAW : ModifyType . DELETE_RAW ; ModelAnnotation annotation ; if ( jqlType == JQLType . UPDATE ) { annotation = method . getAnnotation ( BindSqlUpdate . class ) ; AssertKripton . assertTrueOrInvalidMethodSignException ( AnnotationUtility . extractAsStringArray ( method , annotation , AnnotationAttributeType . FIELDS ) . size ( ) == 0 , method , " can not use attribute %s in this kind of query definition" , AnnotationAttributeType . FIELDS . getValue ( ) ) ; AssertKripton . assertTrueOrInvalidMethodSignException ( AnnotationUtility . extractAsStringArray ( method , annotation , AnnotationAttributeType . EXCLUDED_FIELDS ) . size ( ) == 0 , method , " can not use attribute %s in this kind of query definition" , AnnotationAttributeType . EXCLUDED_FIELDS . getValue ( ) ) ; } else { annotation = method . getAnnotation ( BindSqlDelete . class ) ; } AssertKripton . failWithInvalidMethodSignException ( method . getParameters ( ) . size ( ) > 1 && TypeUtility . isEquals ( method . getParameters ( ) . get ( 0 ) . value1 , daoDefinition . getEntityClassName ( ) ) , method ) ; } else if ( count == 1 ) { updateResultType = jqlType == JQLType . UPDATE ? ModifyType . UPDATE_BEAN : ModifyType . DELETE_BEAN ; AssertKripton . assertTrueOrInvalidMethodSignException ( method . getParameters ( ) . size ( ) == 1 + ( method . hasDynamicWhereConditions ( ) ? 1 : 0 ) + ( method . hasDynamicWhereArgs ( ) ? 1 : 0 ) , method , " expected only one parameter of %s type" , daoDefinition . getEntityClassName ( ) ) ; } else { throw ( new InvalidMethodSignException ( method , "only one parameter of type " + typeName ( entity . getElement ( ) ) + " can be used" ) ) ; } return updateResultType ; }
|
Detect method type .
|
4,380
|
public static void checkContentProviderVarsAndArguments ( final SQLiteModelMethod method , List < JQLPlaceHolder > placeHolders ) { AssertKripton . assertTrue ( placeHolders . size ( ) == method . contentProviderUriVariables . size ( ) , "In '%s.%s' content provider URI path variables and variables used in where conditions are different. If SQL uses parameters, they must be defined in URI path." , method . getParent ( ) . getName ( ) , method . getName ( ) ) ; }
|
Check content provider vars and arguments .
|
4,381
|
static void generateInitForDynamicWhereVariables ( SQLiteModelMethod method , MethodSpec . Builder methodBuilder , String dynamiWhereName , String dynamicWhereArgsName ) { GenerationPartMarks . begin ( methodBuilder , GenerationPartMarks . CODE_001 ) ; if ( method . hasDynamicWhereConditions ( ) ) { methodBuilder . addCode ( "// initialize dynamic where\n" ) ; methodBuilder . addStatement ( "String _sqlDynamicWhere=$L" , dynamiWhereName ) ; } if ( method . hasDynamicWhereArgs ( ) ) { methodBuilder . addCode ( "// initialize dynamic where args\n" ) ; methodBuilder . addStatement ( "String[] _sqlDynamicWhereArgs=$L" , dynamicWhereArgsName ) ; } GenerationPartMarks . end ( methodBuilder , GenerationPartMarks . CODE_001 ) ; }
|
Generate init for dynamic where variables .
|
4,382
|
public static void generateLogForModifiers ( final SQLiteModelMethod method , MethodSpec . Builder methodBuilder ) { JQLChecker jqlChecker = JQLChecker . getInstance ( ) ; final One < Boolean > usedInWhere = new One < Boolean > ( false ) ; methodBuilder . addCode ( "\n// display log\n" ) ; String sqlForLog = jqlChecker . replace ( method , method . jql , new JQLReplacerListenerImpl ( method ) { public String onColumnNameToUpdate ( String columnName ) { return currentEntity . findPropertyByName ( columnName ) . columnName ; } public String onColumnName ( String columnName ) { return currentSchema . findColumnNameByPropertyName ( method , columnName ) ; } public String onBindParameter ( String bindParameterName , boolean inStatement ) { if ( usedInWhere . value0 ) { return "?" ; } else { String paramName = bindParameterName ; if ( paramName . contains ( "." ) ) { String [ ] a = paramName . split ( "\\." ) ; if ( a . length == 2 ) { paramName = a [ 1 ] ; } } SQLProperty property = currentEntity . findPropertyByName ( paramName ) ; AssertKripton . assertTrueOrUnknownPropertyInJQLException ( property != null , method , bindParameterName ) ; return ":" + property . columnName ; } } public void onWhereStatementBegin ( Where_stmtContext ctx ) { usedInWhere . value0 = true ; } public void onWhereStatementEnd ( Where_stmtContext ctx ) { usedInWhere . value0 = false ; } } ) ; if ( method . jql . dynamicReplace . containsKey ( JQLDynamicStatementType . DYNAMIC_WHERE ) ) { methodBuilder . addStatement ( "$T.info($S, $L)" , Logger . class , sqlForLog . replace ( method . jql . dynamicReplace . get ( JQLDynamicStatementType . DYNAMIC_WHERE ) , "%s" ) , "StringUtils.ifNotEmptyAppend(_sqlDynamicWhere,\" AND \")" ) ; } else { methodBuilder . addStatement ( "$T.info($S)" , Logger . class , sqlForLog ) ; } }
|
generate sql log .
|
4,383
|
public static void generate ( Elements elementUtils , Filer filer , SQLiteDatabaseSchema schema , Set < GeneratedTypeElement > generatedEntities ) throws Exception { BindTableGenerator visitor = new BindTableGenerator ( elementUtils , filer , schema ) ; List < SQLiteEntity > orderedEntities = BindDataSourceBuilder . orderEntitiesList ( schema ) ; for ( SQLiteEntity item : orderedEntities ) { visitor . visit ( schema , item ) ; } for ( GeneratedTypeElement genItem : generatedEntities ) { visitor . visit ( schema , genItem ) ; } }
|
Generate table for entities .
|
4,384
|
public static ClassName tableClassName ( SQLiteDaoDefinition dao , SQLiteEntity entity ) { String entityName = BindDataSourceSubProcessor . generateEntityQualifiedName ( dao , entity ) ; return TypeUtility . className ( entityName + SUFFIX ) ; }
|
Table class name .
|
4,385
|
private void generateColumnsArray ( Finder < SQLProperty > entity ) { Builder sp = FieldSpec . builder ( ArrayTypeName . of ( String . class ) , "COLUMNS" , Modifier . STATIC , Modifier . PRIVATE , Modifier . FINAL ) ; String s = "" ; StringBuilder buffer = new StringBuilder ( ) ; for ( SQLProperty property : entity . getCollection ( ) ) { buffer . append ( s + "COLUMN_" + columnNameToUpperCaseConverter . convert ( property . getName ( ) ) ) ; s = ", " ; } classBuilder . addField ( sp . addJavadoc ( "Columns array\n" ) . initializer ( "{" + buffer . toString ( ) + "}" ) . build ( ) ) ; classBuilder . addMethod ( MethodSpec . methodBuilder ( "columns" ) . addModifiers ( Modifier . PUBLIC ) . addJavadoc ( "Columns array\n" ) . addAnnotation ( Override . class ) . returns ( ArrayTypeName . of ( String . class ) ) . addStatement ( "return COLUMNS" ) . build ( ) ) ; classBuilder . addMethod ( MethodSpec . methodBuilder ( "name" ) . addModifiers ( Modifier . PUBLIC ) . addJavadoc ( "table name\n" ) . addAnnotation ( Override . class ) . returns ( TypeName . get ( String . class ) ) . addStatement ( "return TABLE_NAME" ) . build ( ) ) ; }
|
generate columns array .
|
4,386
|
public static Triple < String , String , String > buildIndexes ( final GeneratedTypeElement entity , boolean unique , int counter ) { Triple < String , String , String > result = new Triple < > ( ) ; result . value0 = "" ; result . value1 = "" ; result . value2 = "" ; List < String > indexes = entity . index ; String uniqueString ; uniqueString = "UNIQUE " ; if ( indexes == null || indexes . size ( ) == 0 ) return result ; List < String > listCreateIndex = new ArrayList < > ( ) ; List < String > listDropIndex = new ArrayList < > ( ) ; for ( String index : indexes ) { String createIndex = String . format ( " CREATE %sINDEX idx_%s_%s on %s (%s)" , uniqueString , entity . getTableName ( ) , counter ++ , entity . getTableName ( ) , index ) ; String dropIndex = String . format ( " DROP INDEX IF EXISTS idx_%s_%s" , entity . getTableName ( ) , counter ) ; listCreateIndex . add ( createIndex ) ; listDropIndex . add ( dropIndex ) ; } result . value0 = StringUtils . join ( listCreateIndex , ";" ) ; result . value1 = StringUtils . join ( listDropIndex , ";" ) ; return result ; }
|
A generated element can have only a primary key and two FK .
|
4,387
|
static void generateModifyQueryCommonPart ( SQLiteModelMethod method , TypeSpec . Builder classBuilder , MethodSpec . Builder methodBuilder ) { boolean updateMode = ( method . jql . operationType == JQLType . UPDATE ) ; SqlModifyBuilder . generateInitForDynamicWhereVariables ( method , methodBuilder , method . dynamicWhereParameterName , method . dynamicWhereArgsParameterName ) ; if ( method . jql . hasDynamicParts ( ) || method . jql . containsSelectOperation ) { if ( method . jql . isWhereConditions ( ) ) { methodBuilder . addStatement ( "$T _sqlBuilder=sqlBuilder()" , StringBuilder . class ) ; } SqlBuilderHelper . generateWhereCondition ( methodBuilder , method , true ) ; SqlModifyBuilder . generateSQL ( method , methodBuilder ) ; } if ( method . isLogEnabled ( ) ) { methodBuilder . addComment ( "log section BEGIN" ) ; methodBuilder . beginControlFlow ( "if (_context.isLogEnabled())" ) ; SqlModifyBuilder . generateLogForModifiers ( method , methodBuilder ) ; if ( method . jql . operationType == JQLType . UPDATE && method . isLogEnabled ( ) ) { SqlBuilderHelper . generateLogForContentValues ( method , methodBuilder ) ; } SqlBuilderHelper . generateLogForWhereParameters ( method , methodBuilder ) ; methodBuilder . endControlFlow ( ) ; methodBuilder . addComment ( "log section END" ) ; } if ( method . jql . hasDynamicParts ( ) || method . jql . containsSelectOperation ) { methodBuilder . addStatement ( "int result = $T.updateDelete(_context, _sql, _contentValues)" , KriptonDatabaseWrapper . class ) ; } else { String psName = method . buildPreparedStatementName ( ) ; methodBuilder . addStatement ( "int result = $T.updateDelete($L, _contentValues)" , KriptonDatabaseWrapper . class , psName ) ; } if ( method . getParent ( ) . getParent ( ) . generateRx ) { if ( updateMode ) { GenericSQLHelper . generateSubjectNext ( method . getEntity ( ) , methodBuilder , SubjectType . UPDATE , "result" ) ; } else { GenericSQLHelper . generateSubjectNext ( method . getEntity ( ) , methodBuilder , SubjectType . DELETE , "result" ) ; } } }
|
Generate modify query common part .
|
4,388
|
public void buildReturnCode ( MethodSpec . Builder methodBuilder , boolean updateMode , SQLiteModelMethod method , TypeName returnType ) { if ( returnType == TypeName . VOID ) { } else if ( isTypeIncludedIn ( returnType , Boolean . TYPE , Boolean . class ) ) { methodBuilder . addJavadoc ( "\n" ) ; if ( updateMode ) methodBuilder . addJavadoc ( "@return <code>true</code> if record is updated, <code>false</code> otherwise" ) ; else methodBuilder . addJavadoc ( "@return <code>true</code> if record is deleted, <code>false</code> otherwise" ) ; methodBuilder . addJavadoc ( "\n" ) ; methodBuilder . addCode ( "return result!=0;\n" ) ; } else if ( isTypeIncludedIn ( returnType , Long . TYPE , Long . class , Integer . TYPE , Integer . class , Short . TYPE , Short . class ) ) { methodBuilder . addJavadoc ( "\n" ) ; if ( updateMode ) { methodBuilder . addJavadoc ( "@return number of updated records" ) ; } else { methodBuilder . addJavadoc ( "@return number of deleted records" ) ; } methodBuilder . addJavadoc ( "\n" ) ; methodBuilder . addCode ( "return result;\n" ) ; } else { throw ( new InvalidMethodSignException ( method , "invalid return type" ) ) ; } }
|
Builds the return code .
|
4,389
|
private String extractSQLForJavaDoc ( final SQLiteModelMethod method ) { final One < Boolean > usedInWhere = new One < > ( false ) ; String sqlForJavaDoc = JQLChecker . getInstance ( ) . replace ( method , method . jql , new JQLReplacerListenerImpl ( method ) { public String onColumnNameToUpdate ( String columnName ) { return currentEntity . findPropertyByName ( columnName ) . columnName ; } public String onColumnName ( String columnName ) { return currentEntity . findPropertyByName ( columnName ) . columnName ; } public String onBindParameter ( String bindParameterName , boolean inStatement ) { if ( ! usedInWhere . value0 ) { if ( bindParameterName . contains ( "." ) ) { String [ ] a = bindParameterName . split ( "\\." ) ; if ( a . length == 2 ) { bindParameterName = a [ 1 ] ; } } return ":" + bindParameterName ; } else { return null ; } } public void onWhereStatementBegin ( Where_stmtContext ctx ) { usedInWhere . value0 = true ; } public void onWhereStatementEnd ( Where_stmtContext ctx ) { usedInWhere . value0 = false ; } ; } ) ; return sqlForJavaDoc ; }
|
Extract SQL for java doc .
|
4,390
|
protected static String generateTag ( ) { StackTraceElement [ ] elements = Thread . currentThread ( ) . getStackTrace ( ) ; String currentPath = elements [ 4 ] . getClassName ( ) ; String method = elements [ 4 ] . getMethodName ( ) ; int line = elements [ 4 ] . getLineNumber ( ) ; String tag = currentPath + ", " + method + " (line " + line + ")" ; tag = tag . substring ( tag . lastIndexOf ( "." ) + 1 ) ; return tag ; }
|
generate tag .
|
4,391
|
@ SuppressWarnings ( "unchecked" ) static < E , M extends BinderMapper < E > > M getMapper ( Class < E > cls ) { M mapper = ( M ) OBJECT_MAPPERS . get ( cls ) ; if ( mapper == null ) { String beanClassName = cls . getName ( ) ; String mapperClassName = cls . getName ( ) + KriptonBinder . MAPPER_CLASS_SUFFIX ; try { Class < E > mapperClass = ( Class < E > ) Class . forName ( mapperClassName ) ; mapper = ( M ) mapperClass . newInstance ( ) ; OBJECT_MAPPERS . put ( cls , mapper ) ; } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; throw new KriptonRuntimeException ( String . format ( "Class '%s' does not exist. Does '%s' have @BindType annotation?" , mapperClassName , beanClassName ) ) ; } catch ( InstantiationException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } } return mapper ; }
|
Gets the mapper .
|
4,392
|
public boolean processSecondRound ( Set < ? extends TypeElement > annotations , RoundEnvironment roundEnv ) { for ( SQLiteDatabaseSchema schema : schemas ) { for ( String daoName : schema . getDaoNameSet ( ) ) { if ( globalDaoGenerated . contains ( daoName ) ) { createSQLEntityFromDao ( schema , schema . getElement ( ) , daoName ) ; createSQLDaoDefinition ( schema , globalBeanElements , globalDaoElements , daoName ) ; } } } return true ; }
|
Process second round .
|
4,393
|
public boolean analyzeSecondRound ( Set < ? extends TypeElement > annotations , RoundEnvironment roundEnv ) { parseBindType ( roundEnv ) ; for ( Element item : roundEnv . getElementsAnnotatedWith ( BindSqlType . class ) ) { if ( item . getKind ( ) != ElementKind . CLASS ) { String msg = String . format ( "%s %s, only class can be annotated with @%s annotation" , item . getKind ( ) , item , BindSqlType . class . getSimpleName ( ) ) ; throw ( new InvalidKindForAnnotationException ( msg ) ) ; } globalBeanElements . put ( item . toString ( ) , ( TypeElement ) item ) ; } Set < ? extends Element > generatedDaos = roundEnv . getElementsAnnotatedWith ( BindGeneratedDao . class ) ; for ( Element item : generatedDaos ) { String keyToReplace = AnnotationUtility . extractAsClassName ( item , BindGeneratedDao . class , AnnotationAttributeType . DAO ) ; globalDaoElements . put ( keyToReplace , ( TypeElement ) item ) ; globalDaoGenerated . add ( keyToReplace ) ; } return false ; }
|
Analyze second round .
|
4,394
|
public boolean analyzeRound ( Set < ? extends TypeElement > annotations , RoundEnvironment roundEnv ) { parseBindType ( roundEnv ) ; for ( Element item : roundEnv . getElementsAnnotatedWith ( BindSqlType . class ) ) { if ( item . getKind ( ) != ElementKind . CLASS ) { String msg = String . format ( "%s %s, only class can be annotated with @%s annotation" , item . getKind ( ) , item , BindSqlType . class . getSimpleName ( ) ) ; throw ( new InvalidKindForAnnotationException ( msg ) ) ; } globalBeanElements . put ( item . toString ( ) , ( TypeElement ) item ) ; } for ( Element item : roundEnv . getElementsAnnotatedWith ( BindDao . class ) ) { if ( item . getAnnotation ( BindGeneratedDao . class ) != null ) continue ; if ( item . getKind ( ) != ElementKind . INTERFACE ) { String msg = String . format ( "%s %s can not be annotated with @%s annotation, because it is not an interface" , item . getKind ( ) , item , BindDao . class . getSimpleName ( ) ) ; throw ( new InvalidKindForAnnotationException ( msg ) ) ; } globalDaoElements . put ( item . toString ( ) , ( TypeElement ) item ) ; } for ( Element item : roundEnv . getElementsAnnotatedWith ( BindDaoMany2Many . class ) ) { if ( item . getKind ( ) != ElementKind . INTERFACE ) { String msg = String . format ( "%s %s can not be annotated with @%s annotation, because it is not an interface" , item . getKind ( ) , item , BindDaoMany2Many . class . getSimpleName ( ) ) ; throw ( new InvalidKindForAnnotationException ( msg ) ) ; } globalDaoElements . put ( item . toString ( ) , ( TypeElement ) item ) ; } for ( Element item : roundEnv . getElementsAnnotatedWith ( BindDataSource . class ) ) { dataSets . add ( ( TypeElement ) item ) ; } if ( dataSets . size ( ) == 0 ) return false ; if ( globalDaoElements . size ( ) == 0 ) { throw ( new NoDaoElementFound ( ) ) ; } return false ; }
|
Analyze round .
|
4,395
|
private void analyzeForeignKey ( SQLiteDatabaseSchema schema ) { for ( SQLiteEntity entity : schema . getEntities ( ) ) { for ( SQLProperty property : entity . getCollection ( ) ) { if ( property . isForeignKey ( ) ) { SQLiteEntity reference = schema . getEntity ( property . foreignParentClassName ) ; AssertKripton . asserTrueOrUnspecifiedBeanException ( reference != null , schema , entity , property . foreignParentClassName ) ; if ( ! entity . equals ( reference ) ) { entity . referedEntities . add ( reference ) ; } } } } for ( SQLiteDaoDefinition dao : schema . getCollection ( ) ) { if ( dao . getElement ( ) . getAnnotation ( BindDaoMany2Many . class ) != null ) { ClassName entity1 = TypeUtility . className ( AnnotationUtility . extractAsClassName ( dao . getElement ( ) , BindDaoMany2Many . class , AnnotationAttributeType . ENTITY_1 ) ) ; ClassName entity2 = TypeUtility . className ( AnnotationUtility . extractAsClassName ( dao . getElement ( ) , BindDaoMany2Many . class , AnnotationAttributeType . ENTITY_2 ) ) ; if ( dao . getEntity ( ) != null ) { checkForeignKeyForM2M ( schema , dao . getEntity ( ) , entity1 ) ; checkForeignKeyForM2M ( schema , dao . getEntity ( ) , entity2 ) ; } } } }
|
Analyze foreign key .
|
4,396
|
private boolean isGeneratedEntity ( String fullName ) { for ( GeneratedTypeElement item : this . generatedEntities ) { if ( item . getQualifiedName ( ) . equals ( fullName ) ) { return true ; } } return false ; }
|
Checks if is generated entity .
|
4,397
|
private void checkForeignKeyForM2M ( SQLiteDatabaseSchema currentSchema , final SQLiteEntity currentEntity , ClassName m2mEntity ) { if ( m2mEntity != null ) { SQLiteEntity temp = currentSchema . getEntity ( m2mEntity . toString ( ) ) ; AssertKripton . asserTrueOrForeignKeyNotFound ( currentEntity . referedEntities . contains ( temp ) , currentEntity , m2mEntity ) ; } }
|
Check foreign key for M 2 M .
|
4,398
|
protected void createSQLDaoDefinition ( SQLiteDatabaseSchema schema , final Map < String , TypeElement > globalBeanElements , final Map < String , TypeElement > globalDaoElements , String daoItem ) { Element daoElement = globalDaoElements . get ( daoItem ) ; if ( daoElement . getKind ( ) != ElementKind . INTERFACE ) { String msg = String . format ( "Class %s: only interfaces can be annotated with @%s annotation" , daoElement . getSimpleName ( ) . toString ( ) , BindDao . class . getSimpleName ( ) ) ; throw ( new InvalidKindForAnnotationException ( msg ) ) ; } M2MEntity entity = M2MEntity . extractEntityManagedByDAO ( ( TypeElement ) daoElement ) ; for ( GeneratedTypeElement genItem : this . generatedEntities ) { if ( genItem . getQualifiedName ( ) . equals ( entity . getQualifiedName ( ) ) ) { schema . generatedEntities . add ( genItem ) ; } } boolean generated = daoElement . getAnnotation ( BindGeneratedDao . class ) != null ; final SQLiteDaoDefinition currentDaoDefinition = new SQLiteDaoDefinition ( schema , daoItem , ( TypeElement ) daoElement , entity . getClassName ( ) . toString ( ) , generated ) ; BindContentProviderPath daoContentProviderPath = daoElement . getAnnotation ( BindContentProviderPath . class ) ; if ( daoContentProviderPath != null ) { currentDaoDefinition . contentProviderEnabled = true ; currentDaoDefinition . contentProviderPath = daoContentProviderPath . path ( ) ; currentDaoDefinition . contentProviderTypeName = daoContentProviderPath . typeName ( ) ; if ( StringUtils . isEmpty ( currentDaoDefinition . contentProviderTypeName ) ) { Converter < String , String > convert = CaseFormat . UPPER_CAMEL . converterTo ( CaseFormat . LOWER_UNDERSCORE ) ; AssertKripton . assertTrue ( currentDaoDefinition . getParent ( ) . contentProvider != null , "DAO '%s' has an inconsistent content provider definition, perhaps you forget to use @%s in data source interface?" , currentDaoDefinition . getElement ( ) . getQualifiedName ( ) , BindContentProvider . class . getSimpleName ( ) ) ; currentDaoDefinition . contentProviderTypeName = currentDaoDefinition . getParent ( ) . contentProvider . authority + "." + convert . convert ( currentDaoDefinition . getSimpleEntityClassName ( ) ) ; } } if ( ! globalBeanElements . containsKey ( currentDaoDefinition . getEntityClassName ( ) ) && ! isGeneratedEntity ( currentDaoDefinition . getEntityClassName ( ) ) ) { throw ( new InvalidBeanTypeException ( currentDaoDefinition ) ) ; } schema . add ( currentDaoDefinition ) ; fillMethods ( currentDaoDefinition , daoElement ) ; BindDaoMany2Many daoMany2Many = daoElement . getAnnotation ( BindDaoMany2Many . class ) ; if ( currentDaoDefinition . getCollection ( ) . size ( ) == 0 && daoMany2Many == null ) { throw ( new DaoDefinitionWithoutAnnotatedMethodException ( currentDaoDefinition ) ) ; } }
|
Create DAO definition .
|
4,399
|
private void fillMethods ( final SQLiteDaoDefinition currentDaoDefinition , Element daoElement ) { final One < Boolean > methodWithAnnotation = new One < Boolean > ( false ) ; SqlBuilderHelper . forEachMethods ( ( TypeElement ) daoElement , new MethodFoundListener ( ) { public void onMethod ( ExecutableElement element ) { if ( excludedMethods . contains ( element . getSimpleName ( ) . toString ( ) ) ) return ; methodWithAnnotation . value0 = false ; final List < ModelAnnotation > annotationList = new ArrayList < > ( ) ; final List < ModelAnnotation > supportAnnotationList = new ArrayList < > ( ) ; AnnotationUtility . forEachAnnotations ( element , new AnnotationFoundListener ( ) { public void onAcceptAnnotation ( Element element , String annotationClassName , Map < String , String > attributes ) { if ( annotationClassName . equals ( BindSqlInsert . class . getCanonicalName ( ) ) || annotationClassName . equals ( BindSqlUpdate . class . getCanonicalName ( ) ) || annotationClassName . equals ( BindSqlDelete . class . getCanonicalName ( ) ) || annotationClassName . equals ( BindSqlSelect . class . getCanonicalName ( ) ) || annotationClassName . equals ( BindContentProviderEntry . class . getCanonicalName ( ) ) ) { if ( ! annotationClassName . equals ( BindContentProviderEntry . class . getCanonicalName ( ) ) ) { methodWithAnnotation . value0 = true ; } ModelAnnotation annotation = new ModelAnnotation ( annotationClassName , attributes ) ; annotationList . add ( annotation ) ; } } } ) ; annotationList . addAll ( supportAnnotationList ) ; final SQLiteModelMethod currentMethod = new SQLiteModelMethod ( currentDaoDefinition , element , annotationList ) ; AssertKripton . assertTrueOrInvalidMethodSignException ( methodWithAnnotation . value0 , currentMethod , "method must be annotated with @%s, @%s, @%s or @%s" , BindSqlSelect . class . getSimpleName ( ) , BindSqlInsert . class . getSimpleName ( ) , BindSqlUpdate . class . getSimpleName ( ) , BindSqlDelete . class . getSimpleName ( ) ) ; addWithCheckMethod ( currentDaoDefinition , currentMethod ) ; } private void addWithCheckMethod ( SQLiteDaoDefinition currentDaoDefinition , SQLiteModelMethod newMethod ) { SQLiteModelMethod oldMethod = currentDaoDefinition . findPropertyByName ( newMethod . getName ( ) ) ; if ( oldMethod != null && oldMethod . getParameters ( ) . size ( ) == newMethod . getParameters ( ) . size ( ) ) { boolean sameParameters = true ; for ( int i = 0 ; i < oldMethod . getParameters ( ) . size ( ) ; i ++ ) { if ( ! oldMethod . getParameters ( ) . get ( i ) . value1 . equals ( newMethod . getParameters ( ) . get ( i ) . value1 ) ) { sameParameters = false ; break ; } } AssertKripton . failWithInvalidMethodSignException ( sameParameters , newMethod , "conflict between generated method and declared method." ) ; } currentDaoDefinition . add ( newMethod ) ; } } ) ; }
|
Fill methods .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.