idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
147,100
public boolean switchToStateAndCheckIfClone ( final Eventable event , StateVertex newState , CrawlerContext context ) { StateVertex cloneState = this . addStateToCurrentState ( newState , event ) ; runOnInvariantViolationPlugins ( context ) ; if ( cloneState == null ) { changeState ( newState ) ; plugins . runOnNewStatePlugins ( context , newState ) ; return true ; } else { changeState ( cloneState ) ; return false ; } }
Adds an edge between the current and new state .
109
10
147,101
@ SuppressWarnings ( "unchecked" ) static void logToFile ( String filename ) { Logger rootLogger = ( Logger ) LoggerFactory . getLogger ( org . slf4j . Logger . ROOT_LOGGER_NAME ) ; FileAppender < ILoggingEvent > fileappender = new FileAppender <> ( ) ; fileappender . setContext ( rootLogger . getLoggerContext ( ) ) ; fileappender . setFile ( filename ) ; fileappender . setName ( "FILE" ) ; ConsoleAppender < ? > console = ( ConsoleAppender < ? > ) rootLogger . getAppender ( "STDOUT" ) ; fileappender . setEncoder ( ( Encoder < ILoggingEvent > ) console . getEncoder ( ) ) ; fileappender . start ( ) ; rootLogger . addAppender ( fileappender ) ; console . stop ( ) ; }
Configure file logging and stop console logging .
206
9
147,102
public static void main ( String [ ] args ) { try { JarRunner runner = new JarRunner ( args ) ; runner . runIfConfigured ( ) ; } catch ( NumberFormatException e ) { System . err . println ( "Could not parse number " + e . getMessage ( ) ) ; System . exit ( 1 ) ; } catch ( RuntimeException e ) { System . err . println ( e . getMessage ( ) ) ; System . exit ( 1 ) ; } }
Main executable method of Crawljax CLI .
101
10
147,103
public static String toPrettyJson ( Object o ) { try { return MAPPER . writerWithDefaultPrettyPrinter ( ) . writeValueAsString ( o ) ; } catch ( JsonProcessingException e ) { LoggerFactory . getLogger ( Serializer . class ) . error ( "Could not serialize the object. This will be ignored and the error will be written instead. Object was {}" , o , e ) ; return "\"" + e . getMessage ( ) + "\"" ; } }
Serialize the object JSON . When an error occures return a string with the given error .
110
19
147,104
private void postTraversalProcessing ( ) { int nc1 = treeSize ; info [ KR ] = new int [ leafCount ] ; info [ RKR ] = new int [ leafCount ] ; int lc = leafCount ; int i = 0 ; // compute left-most leaf descendants // go along the left-most path, remember each node and assign to it the path's // leaf // compute right-most leaf descendants (in reversed postorder) for ( i = 0 ; i < treeSize ; i ++ ) { if ( paths [ LEFT ] [ i ] == - 1 ) { info [ POST2_LLD ] [ i ] = i ; } else { info [ POST2_LLD ] [ i ] = info [ POST2_LLD ] [ paths [ LEFT ] [ i ] ] ; } if ( paths [ RIGHT ] [ i ] == - 1 ) { info [ RPOST2_RLD ] [ treeSize - 1 - info [ POST2_PRE ] [ i ] ] = ( treeSize - 1 - info [ POST2_PRE ] [ i ] ) ; } else { info [ RPOST2_RLD ] [ treeSize - 1 - info [ POST2_PRE ] [ i ] ] = info [ RPOST2_RLD ] [ treeSize - 1 - info [ POST2_PRE ] [ paths [ RIGHT ] [ i ] ] ] ; } } // compute key root nodes // compute reversed key root nodes (in revrsed postorder) boolean [ ] visited = new boolean [ nc1 ] ; boolean [ ] visitedR = new boolean [ nc1 ] ; Arrays . fill ( visited , false ) ; int k = lc - 1 ; int kR = lc - 1 ; for ( i = nc1 - 1 ; i >= 0 ; i -- ) { if ( ! visited [ info [ POST2_LLD ] [ i ] ] ) { info [ KR ] [ k ] = i ; visited [ info [ POST2_LLD ] [ i ] ] = true ; k -- ; } if ( ! visitedR [ info [ RPOST2_RLD ] [ i ] ] ) { info [ RKR ] [ kR ] = i ; visitedR [ info [ RPOST2_RLD ] [ i ] ] = true ; kR -- ; } } // compute minimal key roots for every subtree // compute minimal reversed key roots for every subtree (in reversed postorder) int parent = - 1 ; int parentR = - 1 ; for ( i = 0 ; i < leafCount ; i ++ ) { parent = info [ KR ] [ i ] ; while ( parent > - 1 && info [ POST2_MIN_KR ] [ parent ] == - 1 ) { info [ POST2_MIN_KR ] [ parent ] = i ; parent = info [ POST2_PARENT ] [ parent ] ; } parentR = info [ RKR ] [ i ] ; while ( parentR > - 1 && info [ RPOST2_MIN_RKR ] [ parentR ] == - 1 ) { info [ RPOST2_MIN_RKR ] [ parentR ] = i ; parentR = info [ POST2_PARENT ] [ info [ RPOST2_POST ] [ parentR ] ] ; // get parent's postorder if ( parentR > - 1 ) { parentR = treeSize - 1 - info [ POST2_PRE ] [ parentR ] ; // if parent exists get its // rev. postorder } } } }
Gathers information that couldn t be collected while tree traversal .
750
14
147,105
static int [ ] toIntArray ( List < Integer > integers ) { int [ ] ints = new int [ integers . size ( ) ] ; int i = 0 ; for ( Integer n : integers ) { ints [ i ++ ] = n ; } return ints ; }
Transforms a list of Integer objects to an array of primitive int values .
59
15
147,106
@ Override public void onNewState ( CrawlerContext context , StateVertex vertex ) { LOG . debug ( "onNewState" ) ; StateBuilder state = outModelCache . addStateIfAbsent ( vertex ) ; visitedStates . putIfAbsent ( state . getName ( ) , vertex ) ; saveScreenshot ( context . getBrowser ( ) , state . getName ( ) , vertex ) ; outputBuilder . persistDom ( state . getName ( ) , context . getBrowser ( ) . getUnStrippedDom ( ) ) ; }
Saves a screenshot of every new state .
117
9
147,107
@ Override public void preStateCrawling ( CrawlerContext context , ImmutableList < CandidateElement > candidateElements , StateVertex state ) { LOG . debug ( "preStateCrawling" ) ; List < CandidateElementPosition > newElements = Lists . newLinkedList ( ) ; LOG . info ( "Prestate found new state {} with {} candidates" , state . getName ( ) , candidateElements . size ( ) ) ; for ( CandidateElement element : candidateElements ) { try { WebElement webElement = getWebElement ( context . getBrowser ( ) , element ) ; if ( webElement != null ) { newElements . add ( findElement ( webElement , element ) ) ; } } catch ( WebDriverException e ) { LOG . info ( "Could not get position for {}" , element , e ) ; } } StateBuilder stateOut = outModelCache . addStateIfAbsent ( state ) ; stateOut . addCandidates ( newElements ) ; LOG . trace ( "preState finished, elements added to state" ) ; }
Logs all the canidate elements so that the plugin knows which elements were the candidate elements .
229
19
147,108
@ Override public void postCrawling ( CrawlSession session , ExitStatus exitStatus ) { LOG . debug ( "postCrawling" ) ; StateFlowGraph sfg = session . getStateFlowGraph ( ) ; checkSFG ( sfg ) ; // TODO: call state abstraction function to get distance matrix and run rscript on it to // create clusters String [ ] [ ] clusters = null ; // generateClusters(session); result = outModelCache . close ( session , exitStatus , clusters ) ; outputBuilder . write ( result , session . getConfig ( ) , clusters ) ; StateWriter writer = new StateWriter ( outputBuilder , sfg , ImmutableMap . copyOf ( visitedStates ) ) ; for ( State state : result . getStates ( ) . values ( ) ) { try { writer . writeHtmlForState ( state ) ; } catch ( Exception Ex ) { LOG . info ( "couldn't write state :" + state . getName ( ) ) ; } } LOG . info ( "Crawl overview plugin has finished" ) ; }
Generated the report .
226
5
147,109
public FormAction setValuesInForm ( Form form ) { FormAction formAction = new FormAction ( ) ; form . setFormAction ( formAction ) ; this . forms . add ( form ) ; return formAction ; }
Links the form with an HTML element which can be clicked .
47
12
147,110
public static Document removeTags ( Document dom , String tagName ) { NodeList list ; try { list = XPathHelper . evaluateXpathExpression ( dom , "//" + tagName . toUpperCase ( ) ) ; while ( list . getLength ( ) > 0 ) { Node sc = list . item ( 0 ) ; if ( sc != null ) { sc . getParentNode ( ) . removeChild ( sc ) ; } list = XPathHelper . evaluateXpathExpression ( dom , "//" + tagName . toUpperCase ( ) ) ; } } catch ( XPathExpressionException e ) { LOGGER . error ( "Error while removing tag " + tagName , e ) ; } return dom ; }
Removes all the given tags from the document .
157
10
147,111
public static byte [ ] getDocumentToByteArray ( Document dom ) { try { TransformerFactory tFactory = TransformerFactory . newInstance ( ) ; Transformer transformer = tFactory . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "no" ) ; transformer . setOutputProperty ( OutputKeys . METHOD , "html" ) ; // TODO should be fixed to read doctype declaration transformer . setOutputProperty ( OutputKeys . DOCTYPE_PUBLIC , "-//W3C//DTD XHTML 1.0 Strict//EN\" " + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" ) ; DOMSource source = new DOMSource ( dom ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Result result = new StreamResult ( out ) ; transformer . transform ( source , result ) ; return out . toByteArray ( ) ; } catch ( TransformerException e ) { LOGGER . error ( "Error while converting the document to a byte array" , e ) ; } return null ; }
Serialize the Document object .
271
6
147,112
public static String addFolderSlashIfNeeded ( String folderName ) { if ( ! "" . equals ( folderName ) && ! folderName . endsWith ( "/" ) ) { return folderName + "/" ; } else { return folderName ; } }
Adds a slash to a path if it doesn t end with a slash .
55
15
147,113
public static String getTemplateAsString ( String fileName ) throws IOException { // in .jar file String fNameJar = getFileNameInPath ( fileName ) ; InputStream inStream = DomUtils . class . getResourceAsStream ( "/" + fNameJar ) ; if ( inStream == null ) { // try to find file normally File f = new File ( fileName ) ; if ( f . exists ( ) ) { inStream = new FileInputStream ( f ) ; } else { throw new IOException ( "Cannot find " + fileName + " or " + fNameJar ) ; } } BufferedReader bufferedReader = new BufferedReader ( new InputStreamReader ( inStream ) ) ; String line ; StringBuilder stringBuilder = new StringBuilder ( ) ; while ( ( line = bufferedReader . readLine ( ) ) != null ) { stringBuilder . append ( line ) . append ( "\n" ) ; } bufferedReader . close ( ) ; return stringBuilder . toString ( ) ; }
Retrieves the content of the filename . Also reads from JAR Searches for the resource in the root folder in the jar
220
26
147,114
public static void writeDocumentToFile ( Document document , String filePathname , String method , int indent ) throws TransformerException , IOException { Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "no" ) ; transformer . setOutputProperty ( OutputKeys . METHOD , method ) ; transformer . transform ( new DOMSource ( document ) , new StreamResult ( new FileOutputStream ( filePathname ) ) ) ; }
Write the document object to a file .
134
8
147,115
public static String getTextContent ( Document document , boolean individualTokens ) { String textContent = null ; if ( individualTokens ) { List < String > tokens = getTextTokens ( document ) ; textContent = StringUtils . join ( tokens , "," ) ; } else { textContent = document . getDocumentElement ( ) . getTextContent ( ) . trim ( ) . replaceAll ( "\\s+" , "," ) ; } return textContent ; }
To get all the textual content in the dom
98
9
147,116
public boolean equivalent ( Element otherElement , boolean logging ) { if ( eventable . getElement ( ) . equals ( otherElement ) ) { if ( logging ) { LOGGER . info ( "Element equal" ) ; } return true ; } if ( eventable . getElement ( ) . equalAttributes ( otherElement ) ) { if ( logging ) { LOGGER . info ( "Element attributes equal" ) ; } return true ; } if ( eventable . getElement ( ) . equalId ( otherElement ) ) { if ( logging ) { LOGGER . info ( "Element ID equal" ) ; } return true ; } if ( ! eventable . getElement ( ) . getText ( ) . equals ( "" ) && eventable . getElement ( ) . equalText ( otherElement ) ) { if ( logging ) { LOGGER . info ( "Element text equal" ) ; } return true ; } return false ; }
Comparator against other element .
193
6
147,117
@ SuppressWarnings ( "unchecked" ) public List < Difference > compare ( ) { Diff diff = new Diff ( this . controlDOM , this . testDOM ) ; DetailedDiff detDiff = new DetailedDiff ( diff ) ; return detDiff . getAllDifferences ( ) ; }
Compare the controlDOM and testDOM and save and return the differences in a list .
64
17
147,118
protected void setInputElementValue ( Node element , FormInput input ) { LOGGER . debug ( "INPUTFIELD: {} ({})" , input . getIdentification ( ) , input . getType ( ) ) ; if ( element == null || input . getInputValues ( ) . isEmpty ( ) ) { return ; } try { switch ( input . getType ( ) ) { case TEXT : case TEXTAREA : case PASSWORD : handleText ( input ) ; break ; case HIDDEN : handleHidden ( input ) ; break ; case CHECKBOX : handleCheckBoxes ( input ) ; break ; case RADIO : handleRadioSwitches ( input ) ; break ; case SELECT : handleSelectBoxes ( input ) ; } } catch ( ElementNotVisibleException e ) { LOGGER . warn ( "Element not visible, input not completed." ) ; } catch ( BrowserConnectionException e ) { throw e ; } catch ( RuntimeException e ) { LOGGER . error ( "Could not input element values" , e ) ; } }
Fills in the element with the InputValues for input
221
11
147,119
private void handleHidden ( FormInput input ) { String text = input . getInputValues ( ) . iterator ( ) . next ( ) . getValue ( ) ; if ( null == text || text . length ( ) == 0 ) { return ; } WebElement inputElement = browser . getWebElement ( input . getIdentification ( ) ) ; JavascriptExecutor js = ( JavascriptExecutor ) browser . getWebDriver ( ) ; js . executeScript ( "arguments[0].setAttribute(arguments[1], arguments[2]);" , inputElement , "value" , text ) ; }
Enter information into the hidden input field .
126
8
147,120
@ Override public EmbeddedBrowser get ( ) { LOGGER . debug ( "Setting up a Browser" ) ; // Retrieve the config values used ImmutableSortedSet < String > filterAttributes = configuration . getCrawlRules ( ) . getPreCrawlConfig ( ) . getFilterAttributeNames ( ) ; long crawlWaitReload = configuration . getCrawlRules ( ) . getWaitAfterReloadUrl ( ) ; long crawlWaitEvent = configuration . getCrawlRules ( ) . getWaitAfterEvent ( ) ; // Determine the requested browser type EmbeddedBrowser browser = null ; EmbeddedBrowser . BrowserType browserType = configuration . getBrowserConfig ( ) . getBrowserType ( ) ; try { switch ( browserType ) { case CHROME : browser = newChromeBrowser ( filterAttributes , crawlWaitReload , crawlWaitEvent , false ) ; break ; case CHROME_HEADLESS : browser = newChromeBrowser ( filterAttributes , crawlWaitReload , crawlWaitEvent , true ) ; break ; case FIREFOX : browser = newFirefoxBrowser ( filterAttributes , crawlWaitReload , crawlWaitEvent , false ) ; break ; case FIREFOX_HEADLESS : browser = newFirefoxBrowser ( filterAttributes , crawlWaitReload , crawlWaitEvent , true ) ; break ; case REMOTE : browser = WebDriverBackedEmbeddedBrowser . withRemoteDriver ( configuration . getBrowserConfig ( ) . getRemoteHubUrl ( ) , filterAttributes , crawlWaitEvent , crawlWaitReload ) ; break ; case PHANTOMJS : browser = newPhantomJSDriver ( filterAttributes , crawlWaitReload , crawlWaitEvent ) ; break ; default : throw new IllegalStateException ( "Unrecognized browser type " + configuration . getBrowserConfig ( ) . getBrowserType ( ) ) ; } } catch ( IllegalStateException e ) { LOGGER . error ( "Crawling with {} failed: " + e . getMessage ( ) , browserType . toString ( ) ) ; throw e ; } /* for Retina display. */ if ( browser instanceof WebDriverBackedEmbeddedBrowser ) { int pixelDensity = this . configuration . getBrowserConfig ( ) . getBrowserOptions ( ) . getPixelDensity ( ) ; if ( pixelDensity != - 1 ) ( ( WebDriverBackedEmbeddedBrowser ) browser ) . setPixelDensity ( pixelDensity ) ; } plugins . runOnBrowserCreatedPlugins ( browser ) ; return browser ; }
Build a new WebDriver based EmbeddedBrowser .
525
10
147,121
public StackTraceElement [ ] asStackTrace ( ) { int i = 1 ; StackTraceElement [ ] list = new StackTraceElement [ this . size ( ) ] ; for ( Eventable e : this ) { list [ this . size ( ) - i ] = new StackTraceElement ( e . getEventType ( ) . toString ( ) , e . getIdentification ( ) . toString ( ) , e . getElement ( ) . toString ( ) , i ) ; i ++ ; } return list ; }
Build a stack trace for this path . This can be used in generating more meaningful exceptions while using Crawljax in conjunction with JUnit for example .
115
31
147,122
public static WebDriverBackedEmbeddedBrowser withRemoteDriver ( String hubUrl , ImmutableSortedSet < String > filterAttributes , long crawlWaitEvent , long crawlWaitReload ) { return WebDriverBackedEmbeddedBrowser . withDriver ( buildRemoteWebDriver ( hubUrl ) , filterAttributes , crawlWaitEvent , crawlWaitReload ) ; }
Create a RemoteWebDriver backed EmbeddedBrowser .
75
10
147,123
public static WebDriverBackedEmbeddedBrowser withDriver ( WebDriver driver , ImmutableSortedSet < String > filterAttributes , long crawlWaitEvent , long crawlWaitReload ) { return new WebDriverBackedEmbeddedBrowser ( driver , filterAttributes , crawlWaitEvent , crawlWaitReload ) ; }
Create a WebDriver backed EmbeddedBrowser .
65
9
147,124
private static RemoteWebDriver buildRemoteWebDriver ( String hubUrl ) { DesiredCapabilities capabilities = new DesiredCapabilities ( ) ; capabilities . setPlatform ( Platform . ANY ) ; URL url ; try { url = new URL ( hubUrl ) ; } catch ( MalformedURLException e ) { LOGGER . error ( "The given hub url of the remote server is malformed can not continue!" , e ) ; return null ; } HttpCommandExecutor executor = null ; try { executor = new HttpCommandExecutor ( url ) ; } catch ( Exception e ) { // TODO Stefan; refactor this catch, this will definitely result in // NullPointers, why // not throw RuntimeException direct? LOGGER . error ( "Received unknown exception while creating the " + "HttpCommandExecutor, can not continue!" , e ) ; return null ; } return new RemoteWebDriver ( executor , capabilities ) ; }
Private used static method for creation of a RemoteWebDriver . Taking care of the default Capabilities and using the HttpCommandExecutor .
200
28
147,125
@ Override public void handlePopups ( ) { /* * try { executeJavaScript("window.alert = function(msg){return true;};" + * "window.confirm = function(msg){return true;};" + * "window.prompt = function(msg){return true;};"); } catch (CrawljaxException e) { * LOGGER.error("Handling of PopUp windows failed", e); } */ /* Workaround: Popups handling currently not supported in PhantomJS. */ if ( browser instanceof PhantomJSDriver ) { return ; } if ( ExpectedConditions . alertIsPresent ( ) . apply ( browser ) != null ) { try { browser . switchTo ( ) . alert ( ) . accept ( ) ; LOGGER . info ( "Alert accepted" ) ; } catch ( Exception e ) { LOGGER . error ( "Handling of PopUp windows failed" ) ; } } }
alert prompt and confirm behave as if the OK button is always clicked .
199
14
147,126
private boolean fireEventWait ( WebElement webElement , Eventable eventable ) throws ElementNotVisibleException , InterruptedException { switch ( eventable . getEventType ( ) ) { case click : try { webElement . click ( ) ; } catch ( ElementNotVisibleException e ) { throw e ; } catch ( WebDriverException e ) { throwIfConnectionException ( e ) ; return false ; } break ; case hover : LOGGER . info ( "EventType hover called but this isn't implemented yet" ) ; break ; default : LOGGER . info ( "EventType {} not supported in WebDriver." , eventable . getEventType ( ) ) ; return false ; } Thread . sleep ( this . crawlWaitEvent ) ; return true ; }
Fires the event and waits for a specified time .
159
11
147,127
private String filterAttributes ( String html ) { String filteredHtml = html ; for ( String attribute : this . filterAttributes ) { String regex = "\\s" + attribute + "=\"[^\"]*\"" ; Pattern p = Pattern . compile ( regex , Pattern . CASE_INSENSITIVE ) ; Matcher m = p . matcher ( html ) ; filteredHtml = m . replaceAll ( "" ) ; } return filteredHtml ; }
Filters attributes from the HTML string .
97
8
147,128
@ Override public synchronized boolean fireEventAndWait ( Eventable eventable ) throws ElementNotVisibleException , NoSuchElementException , InterruptedException { try { boolean handleChanged = false ; boolean result = false ; if ( eventable . getRelatedFrame ( ) != null && ! eventable . getRelatedFrame ( ) . equals ( "" ) ) { LOGGER . debug ( "switching to frame: " + eventable . getRelatedFrame ( ) ) ; try { switchToFrame ( eventable . getRelatedFrame ( ) ) ; } catch ( NoSuchFrameException e ) { LOGGER . debug ( "Frame not found, possibly while back-tracking.." , e ) ; // TODO Stefan, This exception is caught to prevent stopping // from working // This was the case on the Gmail case; find out if not switching // (catching) // Results in good performance... } handleChanged = true ; } WebElement webElement = browser . findElement ( eventable . getIdentification ( ) . getWebDriverBy ( ) ) ; if ( webElement != null ) { result = fireEventWait ( webElement , eventable ) ; } if ( handleChanged ) { browser . switchTo ( ) . defaultContent ( ) ; } return result ; } catch ( ElementNotVisibleException | NoSuchElementException e ) { throw e ; } catch ( WebDriverException e ) { throwIfConnectionException ( e ) ; return false ; } }
Fires an event on an element using its identification .
303
11
147,129
@ Override public Object executeJavaScript ( String code ) throws CrawljaxException { try { JavascriptExecutor js = ( JavascriptExecutor ) browser ; return js . executeScript ( code ) ; } catch ( WebDriverException e ) { throwIfConnectionException ( e ) ; throw new CrawljaxException ( e ) ; } }
Execute JavaScript in the browser .
72
7
147,130
private InputValue getInputValue ( FormInput input ) { /* Get the DOM element from Selenium. */ WebElement inputElement = browser . getWebElement ( input . getIdentification ( ) ) ; switch ( input . getType ( ) ) { case TEXT : case PASSWORD : case HIDDEN : case SELECT : case TEXTAREA : return new InputValue ( inputElement . getAttribute ( "value" ) ) ; case RADIO : case CHECKBOX : default : String value = inputElement . getAttribute ( "value" ) ; Boolean checked = inputElement . isSelected ( ) ; return new InputValue ( value , checked ) ; } }
Generates the InputValue for the form input by inspecting the current value of the corresponding WebElement on the DOM .
139
23
147,131
public static Properties loadProps ( String filename ) { Properties props = new Properties ( ) ; FileInputStream fis = null ; try { fis = new FileInputStream ( filename ) ; props . load ( fis ) ; return props ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } finally { Closer . closeQuietly ( fis ) ; } }
loading Properties from files
84
4
147,132
public static Properties getProps ( Properties props , String name , Properties defaultProperties ) { final String propString = props . getProperty ( name ) ; if ( propString == null ) return defaultProperties ; String [ ] propValues = propString . split ( "," ) ; if ( propValues . length < 1 ) { throw new IllegalArgumentException ( "Illegal format of specifying properties '" + propString + "'" ) ; } Properties properties = new Properties ( ) ; for ( int i = 0 ; i < propValues . length ; i ++ ) { String [ ] prop = propValues [ i ] . split ( "=" ) ; if ( prop . length != 2 ) throw new IllegalArgumentException ( "Illegal format of specifying properties '" + propValues [ i ] + "'" ) ; properties . put ( prop [ 0 ] , prop [ 1 ] ) ; } return properties ; }
Get a property of type java . util . Properties or return the default if no such property is defined
192
20
147,133
public static String getString ( Properties props , String name , String defaultValue ) { return props . containsKey ( name ) ? props . getProperty ( name ) : defaultValue ; }
Get a string property or if no such property is defined return the given default value
38
16
147,134
public static int read ( ReadableByteChannel channel , ByteBuffer buffer ) throws IOException { int count = channel . read ( buffer ) ; if ( count == - 1 ) throw new EOFException ( "Received -1 when reading from channel, socket has likely been closed." ) ; return count ; }
read data from channel to buffer
64
6
147,135
public static void writeShortString ( ByteBuffer buffer , String s ) { if ( s == null ) { buffer . putShort ( ( short ) - 1 ) ; } else if ( s . length ( ) > Short . MAX_VALUE ) { throw new IllegalArgumentException ( "String exceeds the maximum size of " + Short . MAX_VALUE + "." ) ; } else { byte [ ] data = getBytes ( s ) ; //topic support non-ascii character buffer . putShort ( ( short ) data . length ) ; buffer . put ( data ) ; } }
Write a size prefixed string where the size is stored as a 2 byte short
122
16
147,136
public static void putUnsignedInt ( ByteBuffer buffer , int index , long value ) { buffer . putInt ( index , ( int ) ( value & 0xffffffff L ) ) ; }
Write the given long value as a 4 byte unsigned integer . Overflow is ignored .
41
17
147,137
public static long crc32 ( byte [ ] bytes , int offset , int size ) { CRC32 crc = new CRC32 ( ) ; crc . update ( bytes , offset , size ) ; return crc . getValue ( ) ; }
Compute the CRC32 of the segment of the byte array given by the specificed size and offset
52
20
147,138
public static Thread newThread ( String name , Runnable runnable , boolean daemon ) { Thread thread = new Thread ( runnable , name ) ; thread . setDaemon ( daemon ) ; return thread ; }
Create a new thread
46
4
147,139
private static void unregisterMBean ( String name ) { MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; try { synchronized ( mbs ) { ObjectName objName = new ObjectName ( name ) ; if ( mbs . isRegistered ( objName ) ) { mbs . unregisterMBean ( objName ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Unregister the mbean with the given name if there is one registered
98
14
147,140
@ SuppressWarnings ( "resource" ) public static FileChannel openChannel ( File file , boolean mutable ) throws IOException { if ( mutable ) { return new RandomAccessFile ( file , "rw" ) . getChannel ( ) ; } return new FileInputStream ( file ) . getChannel ( ) ; }
open a readable or writeable FileChannel
69
8
147,141
@ SuppressWarnings ( "unchecked" ) public static < E > E getObject ( String className ) { if ( className == null ) { return ( E ) null ; } try { return ( E ) Class . forName ( className ) . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } }
create an instance from the className
115
7
147,142
public static String md5 ( byte [ ] source ) { try { MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . update ( source ) ; byte tmp [ ] = md . digest ( ) ; char str [ ] = new char [ 32 ] ; int k = 0 ; for ( byte b : tmp ) { str [ k ++ ] = hexDigits [ b >>> 4 & 0xf ] ; str [ k ++ ] = hexDigits [ b & 0xf ] ; } return new String ( str ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( e ) ; } }
digest message with MD5
135
6
147,143
public void append ( LogSegment segment ) { while ( true ) { List < LogSegment > curr = contents . get ( ) ; List < LogSegment > updated = new ArrayList < LogSegment > ( curr ) ; updated . add ( segment ) ; if ( contents . compareAndSet ( curr , updated ) ) { return ; } } }
Append the given item to the end of the list
78
11
147,144
public List < LogSegment > trunc ( int newStart ) { if ( newStart < 0 ) { throw new IllegalArgumentException ( "Starting index must be positive." ) ; } while ( true ) { List < LogSegment > curr = contents . get ( ) ; int newLength = Math . max ( curr . size ( ) - newStart , 0 ) ; List < LogSegment > updatedList = new ArrayList < LogSegment > ( curr . subList ( Math . min ( newStart , curr . size ( ) - 1 ) , curr . size ( ) ) ) ; if ( contents . compareAndSet ( curr , updatedList ) ) { return curr . subList ( 0 , curr . size ( ) - newLength ) ; } } }
Delete the first n items from the list
169
8
147,145
public LogSegment getLastView ( ) { List < LogSegment > views = getView ( ) ; return views . get ( views . size ( ) - 1 ) ; }
get the last segment at the moment
38
7
147,146
private void cleanupLogs ( ) throws IOException { logger . trace ( "Beginning log cleanup..." ) ; int total = 0 ; Iterator < Log > iter = getLogIterator ( ) ; long startMs = System . currentTimeMillis ( ) ; while ( iter . hasNext ( ) ) { Log log = iter . next ( ) ; total += cleanupExpiredSegments ( log ) + cleanupSegmentsToMaintainSize ( log ) ; } if ( total > 0 ) { logger . warn ( "Log cleanup completed. " + total + " files deleted in " + ( System . currentTimeMillis ( ) - startMs ) / 1000 + " seconds" ) ; } else { logger . trace ( "Log cleanup completed. " + total + " files deleted in " + ( System . currentTimeMillis ( ) - startMs ) / 1000 + " seconds" ) ; } }
Runs through the log removing segments older than a certain age
187
12
147,147
private int cleanupSegmentsToMaintainSize ( final Log log ) throws IOException { if ( logRetentionSize < 0 || log . size ( ) < logRetentionSize ) return 0 ; List < LogSegment > toBeDeleted = log . markDeletedWhile ( new LogSegmentFilter ( ) { long diff = log . size ( ) - logRetentionSize ; public boolean filter ( LogSegment segment ) { diff -= segment . size ( ) ; return diff >= 0 ; } } ) ; return deleteSegments ( log , toBeDeleted ) ; }
Runs through the log removing segments until the size of the log is at least logRetentionSize bytes in size
122
23
147,148
private int deleteSegments ( Log log , List < LogSegment > segments ) { int total = 0 ; for ( LogSegment segment : segments ) { boolean deleted = false ; try { try { segment . getMessageSet ( ) . close ( ) ; } catch ( IOException e ) { logger . warn ( e . getMessage ( ) , e ) ; } if ( ! segment . getFile ( ) . delete ( ) ) { deleted = true ; } else { total += 1 ; } } finally { logger . warn ( String . format ( "DELETE_LOG[%s] %s => %s" , log . name , segment . getFile ( ) . getAbsolutePath ( ) , deleted ) ) ; } } return total ; }
Attemps to delete all provided segments from a log and returns how many it was able to
160
19
147,149
public void startup ( ) { if ( config . getEnableZookeeper ( ) ) { serverRegister . registerBrokerInZk ( ) ; for ( String topic : getAllTopics ( ) ) { serverRegister . processTask ( new TopicTask ( TopicTask . TaskType . CREATE , topic ) ) ; } startupLatch . countDown ( ) ; } logger . debug ( "Starting log flusher every {} ms with the following overrides {}" , config . getFlushSchedulerThreadRate ( ) , logFlushIntervalMap ) ; logFlusherScheduler . scheduleWithRate ( new Runnable ( ) { public void run ( ) { flushAllLogs ( false ) ; } } , config . getFlushSchedulerThreadRate ( ) , config . getFlushSchedulerThreadRate ( ) ) ; }
Register this broker in ZK for the first time .
182
11
147,150
public void flushAllLogs ( final boolean force ) { Iterator < Log > iter = getLogIterator ( ) ; while ( iter . hasNext ( ) ) { Log log = iter . next ( ) ; try { boolean needFlush = force ; if ( ! needFlush ) { long timeSinceLastFlush = System . currentTimeMillis ( ) - log . getLastFlushedTime ( ) ; Integer logFlushInterval = logFlushIntervalMap . get ( log . getTopicName ( ) ) ; if ( logFlushInterval == null ) { logFlushInterval = config . getDefaultFlushIntervalMs ( ) ; } final String flushLogFormat = "[%s] flush interval %d, last flushed %d, need flush? %s" ; needFlush = timeSinceLastFlush >= logFlushInterval . intValue ( ) ; logger . trace ( String . format ( flushLogFormat , log . getTopicName ( ) , logFlushInterval , log . getLastFlushedTime ( ) , needFlush ) ) ; } if ( needFlush ) { log . flush ( ) ; } } catch ( IOException ioe ) { logger . error ( "Error flushing topic " + log . getTopicName ( ) , ioe ) ; logger . error ( "Halting due to unrecoverable I/O error while flushing logs: " + ioe . getMessage ( ) , ioe ) ; Runtime . getRuntime ( ) . halt ( 1 ) ; } catch ( Exception e ) { logger . error ( "Error flushing topic " + log . getTopicName ( ) , e ) ; } } }
flush all messages to disk
358
5
147,151
public ILog getLog ( String topic , int partition ) { TopicNameValidator . validate ( topic ) ; Pool < Integer , Log > p = getLogPool ( topic , partition ) ; return p == null ? null : p . get ( partition ) ; }
Get the log if exists or return null
55
8
147,152
public ILog getOrCreateLog ( String topic , int partition ) throws IOException { final int configPartitionNumber = getPartition ( topic ) ; if ( partition >= configPartitionNumber ) { throw new IOException ( "partition is bigger than the number of configuration: " + configPartitionNumber ) ; } boolean hasNewTopic = false ; Pool < Integer , Log > parts = getLogPool ( topic , partition ) ; if ( parts == null ) { Pool < Integer , Log > found = logs . putIfNotExists ( topic , new Pool < Integer , Log > ( ) ) ; if ( found == null ) { hasNewTopic = true ; } parts = logs . get ( topic ) ; } // Log log = parts . get ( partition ) ; if ( log == null ) { log = createLog ( topic , partition ) ; Log found = parts . putIfNotExists ( partition , log ) ; if ( found != null ) { Closer . closeQuietly ( log , logger ) ; log = found ; } else { logger . info ( format ( "Created log for [%s-%d], now create other logs if necessary" , topic , partition ) ) ; final int configPartitions = getPartition ( topic ) ; for ( int i = 0 ; i < configPartitions ; i ++ ) { getOrCreateLog ( topic , i ) ; } } } if ( hasNewTopic && config . getEnableZookeeper ( ) ) { topicRegisterTasks . add ( new TopicTask ( TopicTask . TaskType . CREATE , topic ) ) ; } return log ; }
Create the log if it does not exist or return back exist log
343
13
147,153
public int createLogs ( String topic , final int partitions , final boolean forceEnlarge ) { TopicNameValidator . validate ( topic ) ; synchronized ( logCreationLock ) { final int configPartitions = getPartition ( topic ) ; if ( configPartitions >= partitions || ! forceEnlarge ) { return configPartitions ; } topicPartitionsMap . put ( topic , partitions ) ; if ( config . getEnableZookeeper ( ) ) { if ( getLogPool ( topic , 0 ) != null ) { //created already topicRegisterTasks . add ( new TopicTask ( TopicTask . TaskType . ENLARGE , topic ) ) ; } else { topicRegisterTasks . add ( new TopicTask ( TopicTask . TaskType . CREATE , topic ) ) ; } } return partitions ; } }
create logs with given partition number
172
6
147,154
public List < Long > getOffsets ( OffsetRequest offsetRequest ) { ILog log = getLog ( offsetRequest . topic , offsetRequest . partition ) ; if ( log != null ) { return log . getOffsetsBefore ( offsetRequest ) ; } return ILog . EMPTY_OFFSETS ; }
read offsets before given time
66
5
147,155
private Send handle ( SelectionKey key , Receive request ) { final short requestTypeId = request . buffer ( ) . getShort ( ) ; final RequestKeys requestType = RequestKeys . valueOf ( requestTypeId ) ; if ( requestLogger . isTraceEnabled ( ) ) { if ( requestType == null ) { throw new InvalidRequestException ( "No mapping found for handler id " + requestTypeId ) ; } String logFormat = "Handling %s request from %s" ; requestLogger . trace ( format ( logFormat , requestType , channelFor ( key ) . socket ( ) . getRemoteSocketAddress ( ) ) ) ; } RequestHandler handlerMapping = requesthandlerFactory . mapping ( requestType , request ) ; if ( handlerMapping == null ) { throw new InvalidRequestException ( "No handler found for request" ) ; } long start = System . nanoTime ( ) ; Send maybeSend = handlerMapping . handler ( requestType , request ) ; stats . recordRequest ( requestType , System . nanoTime ( ) - start ) ; return maybeSend ; }
Handle a completed request producing an optional response
231
8
147,156
public static Authentication build ( String crypt ) throws IllegalArgumentException { if ( crypt == null ) { return new PlainAuth ( null ) ; } String [ ] value = crypt . split ( ":" ) ; if ( value . length == 2 ) { String type = value [ 0 ] . trim ( ) ; String password = value [ 1 ] . trim ( ) ; if ( password != null && password . length ( ) > 0 ) { if ( "plain" . equals ( type ) ) { return new PlainAuth ( password ) ; } if ( "md5" . equals ( type ) ) { return new Md5Auth ( password ) ; } if ( "crc32" . equals ( type ) ) { return new Crc32Auth ( Long . parseLong ( password ) ) ; } } } throw new IllegalArgumentException ( "error password: " + crypt ) ; }
build an Authentication .
185
4
147,157
public static Broker createBroker ( int id , String brokerInfoString ) { String [ ] brokerInfo = brokerInfoString . split ( ":" ) ; String creator = brokerInfo [ 0 ] . replace ( ' ' , ' ' ) ; String hostname = brokerInfo [ 1 ] . replace ( ' ' , ' ' ) ; String port = brokerInfo [ 2 ] ; boolean autocreated = Boolean . valueOf ( brokerInfo . length > 3 ? brokerInfo [ 3 ] : "true" ) ; return new Broker ( id , creator , hostname , Integer . parseInt ( port ) , autocreated ) ; }
create a broker with given broker info
133
7
147,158
public static StringConsumers buildConsumer ( final String zookeeperConfig , // final String topic , // final String groupId , // final IMessageListener < String > listener ) { return buildConsumer ( zookeeperConfig , topic , groupId , listener , 2 ) ; }
create a consumer
57
3
147,159
public MessageSet read ( long readOffset , long size ) throws IOException { return new FileMessageSet ( channel , this . offset + readOffset , // Math . min ( this . offset + readOffset + size , highWaterMark ( ) ) , false , new AtomicBoolean ( false ) ) ; }
read message from file
64
4
147,160
public long [ ] append ( MessageSet messages ) throws IOException { checkMutable ( ) ; long written = 0L ; while ( written < messages . getSizeInBytes ( ) ) written += messages . writeTo ( channel , 0 , messages . getSizeInBytes ( ) ) ; long beforeOffset = setSize . getAndAdd ( written ) ; return new long [ ] { written , beforeOffset } ; }
Append this message to the message set
87
8
147,161
public void flush ( ) throws IOException { checkMutable ( ) ; long startTime = System . currentTimeMillis ( ) ; channel . force ( true ) ; long elapsedTime = System . currentTimeMillis ( ) - startTime ; LogFlushStats . recordFlushRequest ( elapsedTime ) ; logger . debug ( "flush time " + elapsedTime ) ; setHighWaterMark . set ( getSizeInBytes ( ) ) ; logger . debug ( "flush high water mark:" + highWaterMark ( ) ) ; }
Commit all written data to the physical disk
112
9
147,162
private long recover ( ) throws IOException { checkMutable ( ) ; long len = channel . size ( ) ; ByteBuffer buffer = ByteBuffer . allocate ( 4 ) ; long validUpTo = 0 ; long next = 0L ; do { next = validateMessage ( channel , validUpTo , len , buffer ) ; if ( next >= 0 ) validUpTo = next ; } while ( next >= 0 ) ; channel . truncate ( validUpTo ) ; setSize . set ( validUpTo ) ; setHighWaterMark . set ( validUpTo ) ; logger . info ( "recover high water mark:" + highWaterMark ( ) ) ; /* This should not be necessary, but fixes bug 6191269 on some OSs. */ channel . position ( validUpTo ) ; needRecover . set ( false ) ; return len - validUpTo ; }
Recover log up to the last complete entry . Truncate off any bytes from any incomplete messages written
184
21
147,163
private long validateMessage ( FileChannel channel , long start , long len , ByteBuffer buffer ) throws IOException { buffer . rewind ( ) ; int read = channel . read ( buffer , start ) ; if ( read < 4 ) return - 1 ; // check that we have sufficient bytes left in the file int size = buffer . getInt ( 0 ) ; if ( size < Message . MinHeaderSize ) return - 1 ; long next = start + 4 + size ; if ( next > len ) return - 1 ; // read the message ByteBuffer messageBuffer = ByteBuffer . allocate ( size ) ; long curr = start + 4 ; while ( messageBuffer . hasRemaining ( ) ) { read = channel . read ( messageBuffer , curr ) ; if ( read < 0 ) throw new IllegalStateException ( "File size changed during recovery!" ) ; else curr += read ; } messageBuffer . rewind ( ) ; Message message = new Message ( messageBuffer ) ; if ( ! message . isValid ( ) ) return - 1 ; else return next ; }
Read validate and discard a single message returning the next valid offset and the message being validated
222
17
147,164
public int createPartitions ( String topic , int partitionNum , boolean enlarge ) throws IOException { KV < Receive , ErrorMapping > response = send ( new CreaterRequest ( topic , partitionNum , enlarge ) ) ; return Utils . deserializeIntArray ( response . k . buffer ( ) ) [ 0 ] ; }
create partitions in the broker
71
5
147,165
public int deleteTopic ( String topic , String password ) throws IOException { KV < Receive , ErrorMapping > response = send ( new DeleterRequest ( topic , password ) ) ; return Utils . deserializeIntArray ( response . k . buffer ( ) ) [ 0 ] ; }
delete topic never used
63
4
147,166
public ByteBuffer payload ( ) { ByteBuffer payload = buffer . duplicate ( ) ; payload . position ( headerSize ( magic ( ) ) ) ; payload = payload . slice ( ) ; payload . limit ( payloadSize ( ) ) ; payload . rewind ( ) ; return payload ; }
get the real data without message header
59
7
147,167
private void validateSegments ( List < LogSegment > segments ) { synchronized ( lock ) { for ( int i = 0 ; i < segments . size ( ) - 1 ; i ++ ) { LogSegment curr = segments . get ( i ) ; LogSegment next = segments . get ( i + 1 ) ; if ( curr . start ( ) + curr . size ( ) != next . start ( ) ) { throw new IllegalStateException ( "The following segments don't validate: " + curr . getFile ( ) . getAbsolutePath ( ) + ", " + next . getFile ( ) . getAbsolutePath ( ) ) ; } } } }
Check that the ranges and sizes add up otherwise we have lost some data somewhere
144
15
147,168
public MessageSet read ( long offset , int length ) throws IOException { List < LogSegment > views = segments . getView ( ) ; LogSegment found = findRange ( views , offset , views . size ( ) ) ; if ( found == null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( format ( "NOT FOUND MessageSet from Log[%s], offset=%d, length=%d" , name , offset , length ) ) ; } return MessageSet . Empty ; } return found . getMessageSet ( ) . read ( offset - found . start ( ) , length ) ; }
read messages beginning from offset
136
5
147,169
public void flush ( ) throws IOException { if ( unflushed . get ( ) == 0 ) return ; synchronized ( lock ) { if ( logger . isTraceEnabled ( ) ) { logger . debug ( "Flushing log '" + name + "' last flushed: " + getLastFlushedTime ( ) + " current time: " + System . currentTimeMillis ( ) ) ; } segments . getLastView ( ) . getMessageSet ( ) . flush ( ) ; unflushed . set ( 0 ) ; lastflushedTime . set ( System . currentTimeMillis ( ) ) ; } }
Flush this log file to the physical disk
128
9
147,170
public static < T extends Range > T findRange ( List < T > ranges , long value , int arraySize ) { if ( ranges . size ( ) < 1 ) return null ; T first = ranges . get ( 0 ) ; T last = ranges . get ( arraySize - 1 ) ; // check out of bounds if ( value < first . start ( ) || value > last . start ( ) + last . size ( ) ) { throw new OffsetOutOfRangeException ( format ( "offset %s is out of range (%s, %s)" , // value , first . start ( ) , last . start ( ) + last . size ( ) ) ) ; } // check at the end if ( value == last . start ( ) + last . size ( ) ) return null ; int low = 0 ; int high = arraySize - 1 ; while ( low <= high ) { int mid = ( high + low ) / 2 ; T found = ranges . get ( mid ) ; if ( found . contains ( value ) ) { return found ; } else if ( value < found . start ( ) ) { high = mid - 1 ; } else { low = mid + 1 ; } } return null ; }
Find a given range object in a list of ranges by a value in that range . Does a binary search over the ranges but instead of checking for equality looks within the range . Takes the array size as an option in case the array grows while searching happens
253
50
147,171
public static String nameFromOffset ( long offset ) { NumberFormat nf = NumberFormat . getInstance ( ) ; nf . setMinimumIntegerDigits ( 20 ) ; nf . setMaximumFractionDigits ( 0 ) ; nf . setGroupingUsed ( false ) ; return nf . format ( offset ) + Log . FileSuffix ; }
Make log segment file name from offset bytes . All this does is pad out the offset number with zeros so that ls sorts the files numerically
77
29
147,172
List < LogSegment > markDeletedWhile ( LogSegmentFilter filter ) throws IOException { synchronized ( lock ) { List < LogSegment > view = segments . getView ( ) ; List < LogSegment > deletable = new ArrayList < LogSegment > ( ) ; for ( LogSegment seg : view ) { if ( filter . filter ( seg ) ) { deletable . add ( seg ) ; } } for ( LogSegment seg : deletable ) { seg . setDeleted ( true ) ; } int numToDelete = deletable . size ( ) ; // // if we are deleting everything, create a new empty segment if ( numToDelete == view . size ( ) ) { if ( view . get ( numToDelete - 1 ) . size ( ) > 0 ) { roll ( ) ; } else { // If the last segment to be deleted is empty and we roll the log, the new segment will have the same // file name. So simply reuse the last segment and reset the modified time. view . get ( numToDelete - 1 ) . getFile ( ) . setLastModified ( System . currentTimeMillis ( ) ) ; numToDelete -= 1 ; } } return segments . trunc ( numToDelete ) ; } }
Delete any log segments matching the given predicate function
272
9
147,173
public void verifyMessageSize ( int maxMessageSize ) { Iterator < MessageAndOffset > shallowIter = internalIterator ( true ) ; while ( shallowIter . hasNext ( ) ) { MessageAndOffset messageAndOffset = shallowIter . next ( ) ; int payloadSize = messageAndOffset . message . payloadSize ( ) ; if ( payloadSize > maxMessageSize ) { throw new MessageSizeTooLargeException ( "payload size of " + payloadSize + " larger than " + maxMessageSize ) ; } } }
check max size of each message
109
6
147,174
public void close ( ) { Closer . closeQuietly ( acceptor ) ; for ( Processor processor : processors ) { Closer . closeQuietly ( processor ) ; } }
Shutdown the socket server
39
5
147,175
public void startup ( ) throws InterruptedException { final int maxCacheConnectionPerThread = serverConfig . getMaxConnections ( ) / processors . length ; logger . debug ( "start {} Processor threads" , processors . length ) ; for ( int i = 0 ; i < processors . length ; i ++ ) { processors [ i ] = new Processor ( handlerFactory , stats , maxRequestSize , maxCacheConnectionPerThread ) ; Utils . newThread ( "jafka-processor-" + i , processors [ i ] , false ) . start ( ) ; } Utils . newThread ( "jafka-acceptor" , acceptor , false ) . start ( ) ; acceptor . awaitStartup ( ) ; }
Start the socket server and waiting for finished
153
8
147,176
public static List < String > getChildrenParentMayNotExist ( ZkClient zkClient , String path ) { try { return zkClient . getChildren ( path ) ; } catch ( ZkNoNodeException e ) { return null ; } }
get children nodes name
54
4
147,177
public static Cluster getCluster ( ZkClient zkClient ) { Cluster cluster = new Cluster ( ) ; List < String > nodes = getChildrenParentMayNotExist ( zkClient , BrokerIdsPath ) ; for ( String node : nodes ) { final String brokerInfoString = readData ( zkClient , BrokerIdsPath + "/" + node ) ; cluster . add ( Broker . createBroker ( Integer . valueOf ( node ) , brokerInfoString ) ) ; } return cluster ; }
read all brokers in the zookeeper
111
8
147,178
public static Map < String , List < String > > getPartitionsForTopics ( ZkClient zkClient , Collection < String > topics ) { Map < String , List < String > > ret = new HashMap < String , List < String > > ( ) ; for ( String topic : topics ) { List < String > partList = new ArrayList < String > ( ) ; List < String > brokers = getChildrenParentMayNotExist ( zkClient , BrokerTopicsPath + "/" + topic ) ; if ( brokers != null ) { for ( String broker : brokers ) { final String parts = readData ( zkClient , BrokerTopicsPath + "/" + topic + "/" + broker ) ; int nParts = Integer . parseInt ( parts ) ; for ( int i = 0 ; i < nParts ; i ++ ) { partList . add ( broker + "-" + i ) ; } } } Collections . sort ( partList ) ; ret . put ( topic , partList ) ; } return ret ; }
read broker info for watching topics
218
6
147,179
public static Map < String , List < String > > getConsumersPerTopic ( ZkClient zkClient , String group ) { ZkGroupDirs dirs = new ZkGroupDirs ( group ) ; List < String > consumers = getChildrenParentMayNotExist ( zkClient , dirs . consumerRegistryDir ) ; // Map < String , List < String > > consumersPerTopicMap = new HashMap < String , List < String > > ( ) ; for ( String consumer : consumers ) { TopicCount topicCount = getTopicCount ( zkClient , group , consumer ) ; for ( Map . Entry < String , Set < String > > e : topicCount . getConsumerThreadIdsPerTopic ( ) . entrySet ( ) ) { final String topic = e . getKey ( ) ; for ( String consumerThreadId : e . getValue ( ) ) { List < String > list = consumersPerTopicMap . get ( topic ) ; if ( list == null ) { list = new ArrayList < String > ( ) ; consumersPerTopicMap . put ( topic , list ) ; } // list . add ( consumerThreadId ) ; } } } // for ( Map . Entry < String , List < String > > e : consumersPerTopicMap . entrySet ( ) ) { Collections . sort ( e . getValue ( ) ) ; } return consumersPerTopicMap ; }
get all consumers for the group
295
6
147,180
public static void createEphemeralPath ( ZkClient zkClient , String path , String data ) { try { zkClient . createEphemeral ( path , Utils . getBytes ( data ) ) ; } catch ( ZkNoNodeException e ) { createParentPath ( zkClient , path ) ; zkClient . createEphemeral ( path , Utils . getBytes ( data ) ) ; } }
Create an ephemeral node with the given path and data . Create parents if necessary .
91
18
147,181
public void addProducer ( Broker broker ) { Properties props = new Properties ( ) ; props . put ( "host" , broker . host ) ; props . put ( "port" , "" + broker . port ) ; props . putAll ( config . getProperties ( ) ) ; if ( sync ) { SyncProducer producer = new SyncProducer ( new SyncProducerConfig ( props ) ) ; logger . info ( "Creating sync producer for broker id = " + broker . id + " at " + broker . host + ":" + broker . port ) ; syncProducers . put ( broker . id , producer ) ; } else { AsyncProducer < V > producer = new AsyncProducer < V > ( new AsyncProducerConfig ( props ) , // new SyncProducer ( new SyncProducerConfig ( props ) ) , // serializer , // eventHandler , // config . getEventHandlerProperties ( ) , // this . callbackHandler , // config . getCbkHandlerProperties ( ) ) ; producer . start ( ) ; logger . info ( "Creating async producer for broker id = " + broker . id + " at " + broker . host + ":" + broker . port ) ; asyncProducers . put ( broker . id , producer ) ; } }
add a new producer either synchronous or asynchronous connecting to the specified broker
274
14
147,182
public void send ( ProducerPoolData < V > ppd ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "send message: " + ppd ) ; } if ( sync ) { Message [ ] messages = new Message [ ppd . data . size ( ) ] ; int index = 0 ; for ( V v : ppd . data ) { messages [ index ] = serializer . toMessage ( v ) ; index ++ ; } ByteBufferMessageSet bbms = new ByteBufferMessageSet ( config . getCompressionCodec ( ) , messages ) ; ProducerRequest request = new ProducerRequest ( ppd . topic , ppd . partition . partId , bbms ) ; SyncProducer producer = syncProducers . get ( ppd . partition . brokerId ) ; if ( producer == null ) { throw new UnavailableProducerException ( "Producer pool has not been initialized correctly. " + "Sync Producer for broker " + ppd . partition . brokerId + " does not exist in the pool" ) ; } producer . send ( request . topic , request . partition , request . messages ) ; } else { AsyncProducer < V > asyncProducer = asyncProducers . get ( ppd . partition . brokerId ) ; for ( V v : ppd . data ) { asyncProducer . send ( ppd . topic , v , ppd . partition . partId ) ; } } }
selects either a synchronous or an asynchronous producer for the specified broker id and calls the send API on the selected producer to publish the data to the specified broker partition
305
33
147,183
public void close ( ) { logger . info ( "Closing all sync producers" ) ; if ( sync ) { for ( SyncProducer p : syncProducers . values ( ) ) { p . close ( ) ; } } else { for ( AsyncProducer < V > p : asyncProducers . values ( ) ) { p . close ( ) ; } } }
Closes all the producers in the pool
79
8
147,184
public ProducerPoolData < V > getProducerPoolData ( String topic , Partition bidPid , List < V > data ) { return new ProducerPoolData < V > ( topic , bidPid , data ) ; }
This constructs and returns the request object for the producer pool
48
11
147,185
public static ProducerRequest readFrom ( ByteBuffer buffer ) { String topic = Utils . readShortString ( buffer ) ; int partition = buffer . getInt ( ) ; int messageSetSize = buffer . getInt ( ) ; ByteBuffer messageSetBuffer = buffer . slice ( ) ; messageSetBuffer . limit ( messageSetSize ) ; buffer . position ( buffer . position ( ) + messageSetSize ) ; return new ProducerRequest ( topic , partition , new ByteBufferMessageSet ( messageSetBuffer ) ) ; }
read a producer request from buffer
107
6
147,186
protected String getExpectedMessage ( ) { StringBuilder syntax = new StringBuilder ( "<tag> " ) ; syntax . append ( getName ( ) ) ; String args = getArgSyntax ( ) ; if ( args != null && args . length ( ) > 0 ) { syntax . append ( ' ' ) ; syntax . append ( args ) ; } return syntax . toString ( ) ; }
Provides a message which describes the expected format and arguments for this command . This is used to provide user feedback when a command request is malformed .
83
30
147,187
public ServerSetup createCopy ( String bindAddress ) { ServerSetup setup = new ServerSetup ( getPort ( ) , bindAddress , getProtocol ( ) ) ; setup . setServerStartupTimeout ( getServerStartupTimeout ( ) ) ; setup . setConnectionTimeout ( getConnectionTimeout ( ) ) ; setup . setReadTimeout ( getReadTimeout ( ) ) ; setup . setWriteTimeout ( getWriteTimeout ( ) ) ; setup . setVerbose ( isVerbose ( ) ) ; return setup ; }
Create a deep copy .
109
5
147,188
public static ServerSetup [ ] verbose ( ServerSetup [ ] serverSetups ) { ServerSetup [ ] copies = new ServerSetup [ serverSetups . length ] ; for ( int i = 0 ; i < serverSetups . length ; i ++ ) { copies [ i ] = serverSetups [ i ] . createCopy ( ) . setVerbose ( true ) ; } return copies ; }
Creates a copy with verbose mode enabled .
84
10
147,189
public void doRun ( Properties properties ) { ServerSetup [ ] serverSetup = new PropertiesBasedServerSetupBuilder ( ) . build ( properties ) ; if ( serverSetup . length == 0 ) { printUsage ( System . out ) ; } else { greenMail = new GreenMail ( serverSetup ) ; log . info ( "Starting GreenMail standalone v{} using {}" , BuildInfo . INSTANCE . getProjectVersion ( ) , Arrays . toString ( serverSetup ) ) ; greenMail . withConfiguration ( new PropertiesBasedGreenMailConfigurationBuilder ( ) . build ( properties ) ) . start ( ) ; } }
Start and configure GreenMail using given properties .
129
9
147,190
private String decodeStr ( String str ) { try { return MimeUtility . decodeText ( str ) ; } catch ( UnsupportedEncodingException e ) { return str ; } }
Returns the decoded string in case it contains non us - ascii characters . Returns the same string if it doesn t or the passed value in case of an UnsupportedEncodingException .
39
39
147,191
public static void copyStream ( final InputStream src , OutputStream dest ) throws IOException { byte [ ] buffer = new byte [ 1024 ] ; int read ; while ( ( read = src . read ( buffer ) ) > - 1 ) { dest . write ( buffer , 0 , read ) ; } dest . flush ( ) ; }
Writes the content of an input stream to an output stream
69
12
147,192
public static int getLineCount ( String str ) { if ( null == str || str . isEmpty ( ) ) { return 0 ; } int count = 1 ; for ( char c : str . toCharArray ( ) ) { if ( ' ' == c ) { count ++ ; } } return count ; }
Counts the number of lines .
65
7
147,193
public static void sendTextEmail ( String to , String from , String subject , String msg , final ServerSetup setup ) { sendMimeMessage ( createTextEmail ( to , from , subject , msg , setup ) ) ; }
Sends a text message using given server setup for SMTP .
47
13
147,194
public static void sendMimeMessage ( MimeMessage mimeMessage ) { try { Transport . send ( mimeMessage ) ; } catch ( MessagingException e ) { throw new IllegalStateException ( "Can not send message " + mimeMessage , e ) ; } }
Send the message using the JavaMail session defined in the message
58
12
147,195
public static void sendMessageBody ( String to , String from , String subject , Object body , String contentType , ServerSetup serverSetup ) { try { Session smtpSession = getSession ( serverSetup ) ; MimeMessage mimeMessage = new MimeMessage ( smtpSession ) ; mimeMessage . setRecipients ( Message . RecipientType . TO , to ) ; mimeMessage . setFrom ( from ) ; mimeMessage . setSubject ( subject ) ; mimeMessage . setContent ( body , contentType ) ; sendMimeMessage ( mimeMessage ) ; } catch ( MessagingException e ) { throw new IllegalStateException ( "Can not send message" , e ) ; } }
Send the message with the given attributes and the given body using the specified SMTP settings
150
17
147,196
public static MimeMultipart createMultipartWithAttachment ( String msg , final byte [ ] attachment , final String contentType , final String filename , String description ) { try { MimeMultipart multiPart = new MimeMultipart ( ) ; MimeBodyPart textPart = new MimeBodyPart ( ) ; multiPart . addBodyPart ( textPart ) ; textPart . setText ( msg ) ; MimeBodyPart binaryPart = new MimeBodyPart ( ) ; multiPart . addBodyPart ( binaryPart ) ; DataSource ds = new DataSource ( ) { @ Override public InputStream getInputStream ( ) throws IOException { return new ByteArrayInputStream ( attachment ) ; } @ Override public OutputStream getOutputStream ( ) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream ( ) ; byteStream . write ( attachment ) ; return byteStream ; } @ Override public String getContentType ( ) { return contentType ; } @ Override public String getName ( ) { return filename ; } } ; binaryPart . setDataHandler ( new DataHandler ( ds ) ) ; binaryPart . setFileName ( filename ) ; binaryPart . setDescription ( description ) ; return multiPart ; } catch ( MessagingException e ) { throw new IllegalArgumentException ( "Can not create multipart message with attachment" , e ) ; } }
Create new multipart with a text part and an attachment
300
11
147,197
public static Session getSession ( final ServerSetup setup , Properties mailProps ) { Properties props = setup . configureJavaMailSessionProperties ( mailProps , false ) ; log . debug ( "Mail session properties are {}" , props ) ; return Session . getInstance ( props , null ) ; }
Gets a JavaMail Session for given server type such as IMAP and additional props for JavaMail .
63
21
147,198
public static void setQuota ( final GreenMailUser user , final Quota quota ) { Session session = GreenMailUtil . getSession ( ServerSetupTest . IMAP ) ; try { Store store = session . getStore ( "imap" ) ; store . connect ( user . getEmail ( ) , user . getPassword ( ) ) ; try { ( ( QuotaAwareStore ) store ) . setQuota ( quota ) ; } finally { store . close ( ) ; } } catch ( Exception ex ) { throw new IllegalStateException ( "Can not set quota " + quota + " for user " + user , ex ) ; } }
Sets a quota for a users .
137
8
147,199
public boolean hasUser ( String userId ) { String normalized = normalizerUserName ( userId ) ; return loginToUser . containsKey ( normalized ) || emailToUser . containsKey ( normalized ) ; }
Checks if user exists .
44
6