repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
crawljax/crawljax
core/src/main/java/com/crawljax/forms/FormHandler.java
FormHandler.setInputElementValue
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); } }
java
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); } }
[ "protected", "void", "setInputElementValue", "(", "Node", "element", ",", "FormInput", "input", ")", "{", "LOGGER", ".", "debug", "(", "\"INPUTFIELD: {} ({})\"", ",", "input", ".", "getIdentification", "(", ")", ",", "input", ".", "getType", "(", ")", ")", "...
Fills in the element with the InputValues for input @param element the node element @param input the input data
[ "Fills", "in", "the", "element", "with", "the", "InputValues", "for", "input" ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/forms/FormHandler.java#L54-L88
train
crawljax/crawljax
core/src/main/java/com/crawljax/forms/FormHandler.java
FormHandler.handleHidden
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); }
java
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); }
[ "private", "void", "handleHidden", "(", "FormInput", "input", ")", "{", "String", "text", "=", "input", ".", "getInputValues", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ".", "getValue", "(", ")", ";", "if", "(", "null", "==", "text"...
Enter information into the hidden input field. @param input The input to enter into the hidden field.
[ "Enter", "information", "into", "the", "hidden", "input", "field", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/forms/FormHandler.java#L135-L144
train
crawljax/crawljax
core/src/main/java/com/crawljax/browser/WebDriverBrowserBuilder.java
WebDriverBrowserBuilder.get
@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; }
java
@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; }
[ "@", "Override", "public", "EmbeddedBrowser", "get", "(", ")", "{", "LOGGER", ".", "debug", "(", "\"Setting up a Browser\"", ")", ";", "// Retrieve the config values used", "ImmutableSortedSet", "<", "String", ">", "filterAttributes", "=", "configuration", ".", "getCr...
Build a new WebDriver based EmbeddedBrowser. @return the new build WebDriver based embeddedBrowser
[ "Build", "a", "new", "WebDriver", "based", "EmbeddedBrowser", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/browser/WebDriverBrowserBuilder.java#L44-L103
train
crawljax/crawljax
core/src/main/java/com/crawljax/core/state/CrawlPath.java
CrawlPath.asStackTrace
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; }
java
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; }
[ "public", "StackTraceElement", "[", "]", "asStackTrace", "(", ")", "{", "int", "i", "=", "1", ";", "StackTraceElement", "[", "]", "list", "=", "new", "StackTraceElement", "[", "this", ".", "size", "(", ")", "]", ";", "for", "(", "Eventable", "e", ":", ...
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. @return a array of StackTraceElements denoting the steps taken by this path. The first element [0] denotes the last {@link Eventable} on this path while the last item denotes the first {@link Eventable} executed.
[ "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", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/CrawlPath.java#L90-L100
train
crawljax/crawljax
core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java
WebDriverBackedEmbeddedBrowser.withRemoteDriver
public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl, ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent, long crawlWaitReload) { return WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl), filterAttributes, crawlWaitEvent, crawlWaitReload); }
java
public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl, ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent, long crawlWaitReload) { return WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl), filterAttributes, crawlWaitEvent, crawlWaitReload); }
[ "public", "static", "WebDriverBackedEmbeddedBrowser", "withRemoteDriver", "(", "String", "hubUrl", ",", "ImmutableSortedSet", "<", "String", ">", "filterAttributes", ",", "long", "crawlWaitEvent", ",", "long", "crawlWaitReload", ")", "{", "return", "WebDriverBackedEmbedde...
Create a RemoteWebDriver backed EmbeddedBrowser. @param hubUrl Url of the server. @param filterAttributes the attributes to be filtered from DOM. @param crawlWaitReload the period to wait after a reload. @param crawlWaitEvent the period to wait after an event is fired. @return The EmbeddedBrowser.
[ "Create", "a", "RemoteWebDriver", "backed", "EmbeddedBrowser", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java#L66-L72
train
crawljax/crawljax
core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java
WebDriverBackedEmbeddedBrowser.withDriver
public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver, ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent, long crawlWaitReload) { return new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent, crawlWaitReload); }
java
public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver, ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent, long crawlWaitReload) { return new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent, crawlWaitReload); }
[ "public", "static", "WebDriverBackedEmbeddedBrowser", "withDriver", "(", "WebDriver", "driver", ",", "ImmutableSortedSet", "<", "String", ">", "filterAttributes", ",", "long", "crawlWaitEvent", ",", "long", "crawlWaitReload", ")", "{", "return", "new", "WebDriverBackedE...
Create a WebDriver backed EmbeddedBrowser. @param driver The WebDriver to use. @param filterAttributes the attributes to be filtered from DOM. @param crawlWaitReload the period to wait after a reload. @param crawlWaitEvent the period to wait after an event is fired. @return The EmbeddedBrowser.
[ "Create", "a", "WebDriver", "backed", "EmbeddedBrowser", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java#L102-L107
train
crawljax/crawljax
core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java
WebDriverBackedEmbeddedBrowser.buildRemoteWebDriver
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); }
java
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", "static", "RemoteWebDriver", "buildRemoteWebDriver", "(", "String", "hubUrl", ")", "{", "DesiredCapabilities", "capabilities", "=", "new", "DesiredCapabilities", "(", ")", ";", "capabilities", ".", "setPlatform", "(", "Platform", ".", "ANY", ")", ";", "...
Private used static method for creation of a RemoteWebDriver. Taking care of the default Capabilities and using the HttpCommandExecutor. @param hubUrl the url of the hub to use. @return the RemoteWebDriver instance.
[ "Private", "used", "static", "method", "for", "creation", "of", "a", "RemoteWebDriver", ".", "Taking", "care", "of", "the", "default", "Capabilities", "and", "using", "the", "HttpCommandExecutor", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java#L145-L170
train
crawljax/crawljax
core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java
WebDriverBackedEmbeddedBrowser.handlePopups
@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"); } } }
java
@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"); } } }
[ "@", "Override", "public", "void", "handlePopups", "(", ")", "{", "/*\n\t\t * try { executeJavaScript(\"window.alert = function(msg){return true;};\" +\n\t\t * \"window.confirm = function(msg){return true;};\" +\n\t\t * \"window.prompt = function(msg){return true;};\"); } catch (CrawljaxException e)...
alert, prompt, and confirm behave as if the OK button is always clicked.
[ "alert", "prompt", "and", "confirm", "behave", "as", "if", "the", "OK", "button", "is", "always", "clicked", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java#L256-L278
train
crawljax/crawljax
core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java
WebDriverBackedEmbeddedBrowser.fireEventWait
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; }
java
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; }
[ "private", "boolean", "fireEventWait", "(", "WebElement", "webElement", ",", "Eventable", "eventable", ")", "throws", "ElementNotVisibleException", ",", "InterruptedException", "{", "switch", "(", "eventable", ".", "getEventType", "(", ")", ")", "{", "case", "click"...
Fires the event and waits for a specified time. @param webElement the element to fire event on. @param eventable The HTML event type (onclick, onmouseover, ...). @return true if firing event is successful. @throws InterruptedException when interrupted during the wait.
[ "Fires", "the", "event", "and", "waits", "for", "a", "specified", "time", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java#L288-L311
train
crawljax/crawljax
core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java
WebDriverBackedEmbeddedBrowser.filterAttributes
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; }
java
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; }
[ "private", "String", "filterAttributes", "(", "String", "html", ")", "{", "String", "filteredHtml", "=", "html", ";", "for", "(", "String", "attribute", ":", "this", ".", "filterAttributes", ")", "{", "String", "regex", "=", "\"\\\\s\"", "+", "attribute", "+...
Filters attributes from the HTML string. @param html The HTML to filter. @return The filtered HTML string.
[ "Filters", "attributes", "from", "the", "HTML", "string", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java#L381-L390
train
crawljax/crawljax
core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java
WebDriverBackedEmbeddedBrowser.fireEventAndWait
@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; } }
java
@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; } }
[ "@", "Override", "public", "synchronized", "boolean", "fireEventAndWait", "(", "Eventable", "eventable", ")", "throws", "ElementNotVisibleException", ",", "NoSuchElementException", ",", "InterruptedException", "{", "try", "{", "boolean", "handleChanged", "=", "false", "...
Fires an event on an element using its identification. @param eventable The eventable. @return true if it is able to fire the event successfully on the element. @throws InterruptedException when interrupted during the wait.
[ "Fires", "an", "event", "on", "an", "element", "using", "its", "identification", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java#L430-L471
train
crawljax/crawljax
core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java
WebDriverBackedEmbeddedBrowser.executeJavaScript
@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); } }
java
@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); } }
[ "@", "Override", "public", "Object", "executeJavaScript", "(", "String", "code", ")", "throws", "CrawljaxException", "{", "try", "{", "JavascriptExecutor", "js", "=", "(", "JavascriptExecutor", ")", "browser", ";", "return", "js", ".", "executeScript", "(", "cod...
Execute JavaScript in the browser. @param code The code to execute. @return The return value of the JavaScript. @throws CrawljaxException when javascript execution failed.
[ "Execute", "JavaScript", "in", "the", "browser", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java#L480-L489
train
crawljax/crawljax
core/src/main/java/com/crawljax/forms/TrainingFormHandler.java
TrainingFormHandler.getInputValue
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); } }
java
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); } }
[ "private", "InputValue", "getInputValue", "(", "FormInput", "input", ")", "{", "/* Get the DOM element from Selenium. */", "WebElement", "inputElement", "=", "browser", ".", "getWebElement", "(", "input", ".", "getIdentification", "(", ")", ")", ";", "switch", "(", ...
Generates the InputValue for the form input by inspecting the current value of the corresponding WebElement on the DOM. @return The current InputValue for the element on the DOM.
[ "Generates", "the", "InputValue", "for", "the", "form", "input", "by", "inspecting", "the", "current", "value", "of", "the", "corresponding", "WebElement", "on", "the", "DOM", "." ]
d339f4f622ca902ccd35322065821e52a62ec543
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/forms/TrainingFormHandler.java#L195-L215
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.loadProps
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); } }
java
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); } }
[ "public", "static", "Properties", "loadProps", "(", "String", "filename", ")", "{", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "FileInputStream", "fis", "=", "null", ";", "try", "{", "fis", "=", "new", "FileInputStream", "(", "filename",...
loading Properties from files @param filename file path @return properties @throws RuntimeException while file not exist or loading fail
[ "loading", "Properties", "from", "files" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L47-L60
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.getProps
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; }
java
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; }
[ "public", "static", "Properties", "getProps", "(", "Properties", "props", ",", "String", "name", ",", "Properties", "defaultProperties", ")", "{", "final", "String", "propString", "=", "props", ".", "getProperty", "(", "name", ")", ";", "if", "(", "propString"...
Get a property of type java.util.Properties or return the default if no such property is defined @param props properties @param name the key @param defaultProperties default property if empty @return value from the property
[ "Get", "a", "property", "of", "type", "java", ".", "util", ".", "Properties", "or", "return", "the", "default", "if", "no", "such", "property", "is", "defined" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L70-L84
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.getString
public static String getString(Properties props, String name, String defaultValue) { return props.containsKey(name) ? props.getProperty(name) : defaultValue; }
java
public static String getString(Properties props, String name, String defaultValue) { return props.containsKey(name) ? props.getProperty(name) : defaultValue; }
[ "public", "static", "String", "getString", "(", "Properties", "props", ",", "String", "name", ",", "String", "defaultValue", ")", "{", "return", "props", ".", "containsKey", "(", "name", ")", "?", "props", ".", "getProperty", "(", "name", ")", ":", "defaul...
Get a string property, or, if no such property is defined, return the given default value @param props the properties @param name the key in the properties @param defaultValue the default value if the key not exists @return value in the props or defaultValue while name not exist
[ "Get", "a", "string", "property", "or", "if", "no", "such", "property", "is", "defined", "return", "the", "given", "default", "value" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L95-L97
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.read
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; }
java
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; }
[ "public", "static", "int", "read", "(", "ReadableByteChannel", "channel", ",", "ByteBuffer", "buffer", ")", "throws", "IOException", "{", "int", "count", "=", "channel", ".", "read", "(", "buffer", ")", ";", "if", "(", "count", "==", "-", "1", ")", "thro...
read data from channel to buffer @param channel readable channel @param buffer bytebuffer @return read size @throws IOException any io exception
[ "read", "data", "from", "channel", "to", "buffer" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L192-L196
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.writeShortString
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); } }
java
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); } }
[ "public", "static", "void", "writeShortString", "(", "ByteBuffer", "buffer", ",", "String", "s", ")", "{", "if", "(", "s", "==", "null", ")", "{", "buffer", ".", "putShort", "(", "(", "short", ")", "-", "1", ")", ";", "}", "else", "if", "(", "s", ...
Write a size prefixed string where the size is stored as a 2 byte short @param buffer The buffer to write to @param s The string to write
[ "Write", "a", "size", "prefixed", "string", "where", "the", "size", "is", "stored", "as", "a", "2", "byte", "short" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L205-L215
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.putUnsignedInt
public static void putUnsignedInt(ByteBuffer buffer, int index, long value) { buffer.putInt(index, (int) (value & 0xffffffffL)); }
java
public static void putUnsignedInt(ByteBuffer buffer, int index, long value) { buffer.putInt(index, (int) (value & 0xffffffffL)); }
[ "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. @param buffer The buffer to write to @param index The position in the buffer at which to begin writing @param value The value to write
[ "Write", "the", "given", "long", "value", "as", "a", "4", "byte", "unsigned", "integer", ".", "Overflow", "is", "ignored", "." ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L285-L287
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.crc32
public static long crc32(byte[] bytes, int offset, int size) { CRC32 crc = new CRC32(); crc.update(bytes, offset, size); return crc.getValue(); }
java
public static long crc32(byte[] bytes, int offset, int size) { CRC32 crc = new CRC32(); crc.update(bytes, offset, size); return crc.getValue(); }
[ "public", "static", "long", "crc32", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "int", "size", ")", "{", "CRC32", "crc", "=", "new", "CRC32", "(", ")", ";", "crc", ".", "update", "(", "bytes", ",", "offset", ",", "size", ")", ";",...
Compute the CRC32 of the segment of the byte array given by the specificed size and offset @param bytes The bytes to checksum @param offset the offset at which to begin checksumming @param size the number of bytes to checksum @return The CRC32
[ "Compute", "the", "CRC32", "of", "the", "segment", "of", "the", "byte", "array", "given", "by", "the", "specificed", "size", "and", "offset" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L308-L312
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.newThread
public static Thread newThread(String name, Runnable runnable, boolean daemon) { Thread thread = new Thread(runnable, name); thread.setDaemon(daemon); return thread; }
java
public static Thread newThread(String name, Runnable runnable, boolean daemon) { Thread thread = new Thread(runnable, name); thread.setDaemon(daemon); return thread; }
[ "public", "static", "Thread", "newThread", "(", "String", "name", ",", "Runnable", "runnable", ",", "boolean", "daemon", ")", "{", "Thread", "thread", "=", "new", "Thread", "(", "runnable", ",", "name", ")", ";", "thread", ".", "setDaemon", "(", "daemon", ...
Create a new thread @param name The name of the thread @param runnable The work for the thread to do @param daemon Should the thread block JVM shutdown? @return The unstarted thread
[ "Create", "a", "new", "thread" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L322-L326
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.unregisterMBean
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(); } }
java
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(); } }
[ "private", "static", "void", "unregisterMBean", "(", "String", "name", ")", "{", "MBeanServer", "mbs", "=", "ManagementFactory", ".", "getPlatformMBeanServer", "(", ")", ";", "try", "{", "synchronized", "(", "mbs", ")", "{", "ObjectName", "objName", "=", "new"...
Unregister the mbean with the given name, if there is one registered @param name The mbean name to unregister @see #registerMBean(Object, String)
[ "Unregister", "the", "mbean", "with", "the", "given", "name", "if", "there", "is", "one", "registered" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L398-L410
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.openChannel
@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(); }
java
@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(); }
[ "@", "SuppressWarnings", "(", "\"resource\"", ")", "public", "static", "FileChannel", "openChannel", "(", "File", "file", ",", "boolean", "mutable", ")", "throws", "IOException", "{", "if", "(", "mutable", ")", "{", "return", "new", "RandomAccessFile", "(", "f...
open a readable or writeable FileChannel @param file file object @param mutable writeable @return open the FileChannel @throws IOException any io exception
[ "open", "a", "readable", "or", "writeable", "FileChannel" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L420-L426
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.getObject
@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); } }
java
@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); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "E", ">", "E", "getObject", "(", "String", "className", ")", "{", "if", "(", "className", "==", "null", ")", "{", "return", "(", "E", ")", "null", ";", "}", "try", "{", "ret...
create an instance from the className @param <E> class of object @param className full class name @return an object or null if className is null
[ "create", "an", "instance", "from", "the", "className" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L447-L461
train
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.md5
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); } }
java
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); } }
[ "public", "static", "String", "md5", "(", "byte", "[", "]", "source", ")", "{", "try", "{", "MessageDigest", "md", "=", "MessageDigest", ".", "getInstance", "(", "\"MD5\"", ")", ";", "md", ".", "update", "(", "source", ")", ";", "byte", "tmp", "[", "...
digest message with MD5 @param source message @return 32 bit MD5 value (lower case)
[ "digest", "message", "with", "MD5" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L525-L541
train
adyliu/jafka
src/main/java/io/jafka/log/SegmentList.java
SegmentList.append
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; } } }
java
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; } } }
[ "public", "void", "append", "(", "LogSegment", "segment", ")", "{", "while", "(", "true", ")", "{", "List", "<", "LogSegment", ">", "curr", "=", "contents", ".", "get", "(", ")", ";", "List", "<", "LogSegment", ">", "updated", "=", "new", "ArrayList", ...
Append the given item to the end of the list @param segment segment to append
[ "Append", "the", "given", "item", "to", "the", "end", "of", "the", "list" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/SegmentList.java#L51-L60
train
adyliu/jafka
src/main/java/io/jafka/log/SegmentList.java
SegmentList.trunc
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); } } }
java
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); } } }
[ "public", "List", "<", "LogSegment", ">", "trunc", "(", "int", "newStart", ")", "{", "if", "(", "newStart", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Starting index must be positive.\"", ")", ";", "}", "while", "(", "true", ")",...
Delete the first n items from the list @param newStart the logsegment who's index smaller than newStart will be deleted. @return the deleted segment
[ "Delete", "the", "first", "n", "items", "from", "the", "list" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/SegmentList.java#L68-L81
train
adyliu/jafka
src/main/java/io/jafka/log/SegmentList.java
SegmentList.getLastView
public LogSegment getLastView() { List<LogSegment> views = getView(); return views.get(views.size() - 1); }
java
public LogSegment getLastView() { List<LogSegment> views = getView(); return views.get(views.size() - 1); }
[ "public", "LogSegment", "getLastView", "(", ")", "{", "List", "<", "LogSegment", ">", "views", "=", "getView", "(", ")", ";", "return", "views", ".", "get", "(", "views", ".", "size", "(", ")", "-", "1", ")", ";", "}" ]
get the last segment at the moment @return the last segment
[ "get", "the", "last", "segment", "at", "the", "moment" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/SegmentList.java#L88-L91
train
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.cleanupLogs
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"); } }
java
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"); } }
[ "private", "void", "cleanupLogs", "(", ")", "throws", "IOException", "{", "logger", ".", "trace", "(", "\"Beginning log cleanup...\"", ")", ";", "int", "total", "=", "0", ";", "Iterator", "<", "Log", ">", "iter", "=", "getLogIterator", "(", ")", ";", "long...
Runs through the log removing segments older than a certain age @throws IOException
[ "Runs", "through", "the", "log", "removing", "segments", "older", "than", "a", "certain", "age" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L252-L266
train
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.cleanupSegmentsToMaintainSize
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); }
java
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); }
[ "private", "int", "cleanupSegmentsToMaintainSize", "(", "final", "Log", "log", ")", "throws", "IOException", "{", "if", "(", "logRetentionSize", "<", "0", "||", "log", ".", "size", "(", ")", "<", "logRetentionSize", ")", "return", "0", ";", "List", "<", "L...
Runs through the log removing segments until the size of the log is at least logRetentionSize bytes in size @throws IOException
[ "Runs", "through", "the", "log", "removing", "segments", "until", "the", "size", "of", "the", "log", "is", "at", "least", "logRetentionSize", "bytes", "in", "size" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L274-L287
train
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.deleteSegments
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; }
java
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; }
[ "private", "int", "deleteSegments", "(", "Log", "log", ",", "List", "<", "LogSegment", ">", "segments", ")", "{", "int", "total", "=", "0", ";", "for", "(", "LogSegment", "segment", ":", "segments", ")", "{", "boolean", "deleted", "=", "false", ";", "t...
Attemps to delete all provided segments from a log and returns how many it was able to
[ "Attemps", "to", "delete", "all", "provided", "segments", "from", "a", "log", "and", "returns", "how", "many", "it", "was", "able", "to" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L310-L331
train
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.startup
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()); }
java
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()); }
[ "public", "void", "startup", "(", ")", "{", "if", "(", "config", ".", "getEnableZookeeper", "(", ")", ")", "{", "serverRegister", ".", "registerBrokerInZk", "(", ")", ";", "for", "(", "String", "topic", ":", "getAllTopics", "(", ")", ")", "{", "serverReg...
Register this broker in ZK for the first time.
[ "Register", "this", "broker", "in", "ZK", "for", "the", "first", "time", "." ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L336-L351
train
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.flushAllLogs
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); } } }
java
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); } } }
[ "public", "void", "flushAllLogs", "(", "final", "boolean", "force", ")", "{", "Iterator", "<", "Log", ">", "iter", "=", "getLogIterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "Log", "log", "=", "iter", ".", "next",...
flush all messages to disk @param force flush anyway(ignore flush interval)
[ "flush", "all", "messages", "to", "disk" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L358-L386
train
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.getLog
public ILog getLog(String topic, int partition) { TopicNameValidator.validate(topic); Pool<Integer, Log> p = getLogPool(topic, partition); return p == null ? null : p.get(partition); }
java
public ILog getLog(String topic, int partition) { TopicNameValidator.validate(topic); Pool<Integer, Log> p = getLogPool(topic, partition); return p == null ? null : p.get(partition); }
[ "public", "ILog", "getLog", "(", "String", "topic", ",", "int", "partition", ")", "{", "TopicNameValidator", ".", "validate", "(", "topic", ")", ";", "Pool", "<", "Integer", ",", "Log", ">", "p", "=", "getLogPool", "(", "topic", ",", "partition", ")", ...
Get the log if exists or return null @param topic topic name @param partition partition index @return a log for the topic or null if not exist
[ "Get", "the", "log", "if", "exists", "or", "return", "null" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L450-L454
train
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.getOrCreateLog
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; }
java
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; }
[ "public", "ILog", "getOrCreateLog", "(", "String", "topic", ",", "int", "partition", ")", "throws", "IOException", "{", "final", "int", "configPartitionNumber", "=", "getPartition", "(", "topic", ")", ";", "if", "(", "partition", ">=", "configPartitionNumber", "...
Create the log if it does not exist or return back exist log @param topic the topic name @param partition the partition id @return read or create a log @throws IOException any IOException
[ "Create", "the", "log", "if", "it", "does", "not", "exist", "or", "return", "back", "exist", "log" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L464-L498
train
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.createLogs
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; } }
java
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; } }
[ "public", "int", "createLogs", "(", "String", "topic", ",", "final", "int", "partitions", ",", "final", "boolean", "forceEnlarge", ")", "{", "TopicNameValidator", ".", "validate", "(", "topic", ")", ";", "synchronized", "(", "logCreationLock", ")", "{", "final...
create logs with given partition number @param topic the topic name @param partitions partition number @param forceEnlarge enlarge the partition number of log if smaller than runtime @return the partition number of the log after enlarging
[ "create", "logs", "with", "given", "partition", "number" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L508-L525
train
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.getOffsets
public List<Long> getOffsets(OffsetRequest offsetRequest) { ILog log = getLog(offsetRequest.topic, offsetRequest.partition); if (log != null) { return log.getOffsetsBefore(offsetRequest); } return ILog.EMPTY_OFFSETS; }
java
public List<Long> getOffsets(OffsetRequest offsetRequest) { ILog log = getLog(offsetRequest.topic, offsetRequest.partition); if (log != null) { return log.getOffsetsBefore(offsetRequest); } return ILog.EMPTY_OFFSETS; }
[ "public", "List", "<", "Long", ">", "getOffsets", "(", "OffsetRequest", "offsetRequest", ")", "{", "ILog", "log", "=", "getLog", "(", "offsetRequest", ".", "topic", ",", "offsetRequest", ".", "partition", ")", ";", "if", "(", "log", "!=", "null", ")", "{...
read offsets before given time @param offsetRequest the offset request @return offsets before given time
[ "read", "offsets", "before", "given", "time" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L584-L590
train
adyliu/jafka
src/main/java/io/jafka/network/Processor.java
Processor.handle
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; }
java
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; }
[ "private", "Send", "handle", "(", "SelectionKey", "key", ",", "Receive", "request", ")", "{", "final", "short", "requestTypeId", "=", "request", ".", "buffer", "(", ")", ".", "getShort", "(", ")", ";", "final", "RequestKeys", "requestType", "=", "RequestKeys...
Handle a completed request producing an optional response
[ "Handle", "a", "completed", "request", "producing", "an", "optional", "response" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/network/Processor.java#L194-L212
train
adyliu/jafka
src/main/java/io/jafka/server/Authentication.java
Authentication.build
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); }
java
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); }
[ "public", "static", "Authentication", "build", "(", "String", "crypt", ")", "throws", "IllegalArgumentException", "{", "if", "(", "crypt", "==", "null", ")", "{", "return", "new", "PlainAuth", "(", "null", ")", ";", "}", "String", "[", "]", "value", "=", ...
build an Authentication. Types: <ul> <li>plain:jafka</li> <li>md5:77be29f6d71ec4e310766ddf881ae6a0</li> <li>crc32:1725717671</li> </ul> @param crypt password style @return an authentication @throws IllegalArgumentException password error
[ "build", "an", "Authentication", "." ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/server/Authentication.java#L87-L109
train
adyliu/jafka
src/main/java/io/jafka/cluster/Broker.java
Broker.createBroker
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); }
java
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); }
[ "public", "static", "Broker", "createBroker", "(", "int", "id", ",", "String", "brokerInfoString", ")", "{", "String", "[", "]", "brokerInfo", "=", "brokerInfoString", ".", "split", "(", "\":\"", ")", ";", "String", "creator", "=", "brokerInfo", "[", "0", ...
create a broker with given broker info @param id broker id @param brokerInfoString broker info format: <b>creatorId:host:port:autocreated</b> @return broker instance with connection config @see #getZKString()
[ "create", "a", "broker", "with", "given", "broker", "info" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/cluster/Broker.java#L119-L126
train
adyliu/jafka
src/main/java/io/jafka/consumer/StringConsumers.java
StringConsumers.buildConsumer
public static StringConsumers buildConsumer( final String zookeeperConfig,// final String topic,// final String groupId, // final IMessageListener<String> listener) { return buildConsumer(zookeeperConfig, topic, groupId, listener, 2); }
java
public static StringConsumers buildConsumer( final String zookeeperConfig,// final String topic,// final String groupId, // final IMessageListener<String> listener) { return buildConsumer(zookeeperConfig, topic, groupId, listener, 2); }
[ "public", "static", "StringConsumers", "buildConsumer", "(", "final", "String", "zookeeperConfig", ",", "//", "final", "String", "topic", ",", "//", "final", "String", "groupId", ",", "//", "final", "IMessageListener", "<", "String", ">", "listener", ")", "{", ...
create a consumer @param zookeeperConfig connect config of zookeeper; ex: 127.0.0.1:2181/jafka @param topic the topic to be watched @param groupId grouping the consumer clients @param listener message listener @return the real consumer
[ "create", "a", "consumer" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/consumer/StringConsumers.java#L126-L132
train
adyliu/jafka
src/main/java/io/jafka/message/FileMessageSet.java
FileMessageSet.read
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)); }
java
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)); }
[ "public", "MessageSet", "read", "(", "long", "readOffset", ",", "long", "size", ")", "throws", "IOException", "{", "return", "new", "FileMessageSet", "(", "channel", ",", "this", ".", "offset", "+", "readOffset", ",", "//", "Math", ".", "min", "(", "this",...
read message from file @param readOffset offset in this channel(file);not the message offset @param size max data size @return messages sharding data with file log @throws IOException reading file failed
[ "read", "message", "from", "file" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/message/FileMessageSet.java#L187-L190
train
adyliu/jafka
src/main/java/io/jafka/message/FileMessageSet.java
FileMessageSet.append
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}; }
java
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}; }
[ "public", "long", "[", "]", "append", "(", "MessageSet", "messages", ")", "throws", "IOException", "{", "checkMutable", "(", ")", ";", "long", "written", "=", "0L", ";", "while", "(", "written", "<", "messages", ".", "getSizeInBytes", "(", ")", ")", "wri...
Append this message to the message set @param messages message to append @return the written size and first offset @throws IOException file write exception
[ "Append", "this", "message", "to", "the", "message", "set" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/message/FileMessageSet.java#L198-L205
train
adyliu/jafka
src/main/java/io/jafka/message/FileMessageSet.java
FileMessageSet.flush
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()); }
java
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()); }
[ "public", "void", "flush", "(", ")", "throws", "IOException", "{", "checkMutable", "(", ")", ";", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "channel", ".", "force", "(", "true", ")", ";", "long", "elapsedTime", "=", "Sy...
Commit all written data to the physical disk @throws IOException any io exception
[ "Commit", "all", "written", "data", "to", "the", "physical", "disk" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/message/FileMessageSet.java#L212-L221
train
adyliu/jafka
src/main/java/io/jafka/message/FileMessageSet.java
FileMessageSet.recover
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; }
java
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; }
[ "private", "long", "recover", "(", ")", "throws", "IOException", "{", "checkMutable", "(", ")", ";", "long", "len", "=", "channel", ".", "size", "(", ")", ";", "ByteBuffer", "buffer", "=", "ByteBuffer", ".", "allocate", "(", "4", ")", ";", "long", "val...
Recover log up to the last complete entry. Truncate off any bytes from any incomplete messages written @throws IOException any exception
[ "Recover", "log", "up", "to", "the", "last", "complete", "entry", ".", "Truncate", "off", "any", "bytes", "from", "any", "incomplete", "messages", "written" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/message/FileMessageSet.java#L239-L257
train
adyliu/jafka
src/main/java/io/jafka/message/FileMessageSet.java
FileMessageSet.validateMessage
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; }
java
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; }
[ "private", "long", "validateMessage", "(", "FileChannel", "channel", ",", "long", "start", ",", "long", "len", ",", "ByteBuffer", "buffer", ")", "throws", "IOException", "{", "buffer", ".", "rewind", "(", ")", ";", "int", "read", "=", "channel", ".", "read...
Read, validate, and discard a single message, returning the next valid offset, and the message being validated @throws IOException any exception
[ "Read", "validate", "and", "discard", "a", "single", "message", "returning", "the", "next", "valid", "offset", "and", "the", "message", "being", "validated" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/message/FileMessageSet.java#L265-L289
train
adyliu/jafka
src/main/java/io/jafka/admin/AdminOperation.java
AdminOperation.createPartitions
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]; }
java
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]; }
[ "public", "int", "createPartitions", "(", "String", "topic", ",", "int", "partitionNum", ",", "boolean", "enlarge", ")", "throws", "IOException", "{", "KV", "<", "Receive", ",", "ErrorMapping", ">", "response", "=", "send", "(", "new", "CreaterRequest", "(", ...
create partitions in the broker @param topic topic name @param partitionNum partition numbers @param enlarge enlarge partition number if broker configuration has setted @return partition number in the broker @throws IOException if an I/O error occurs
[ "create", "partitions", "in", "the", "broker" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/admin/AdminOperation.java#L51-L54
train
adyliu/jafka
src/main/java/io/jafka/admin/AdminOperation.java
AdminOperation.deleteTopic
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]; }
java
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]; }
[ "public", "int", "deleteTopic", "(", "String", "topic", ",", "String", "password", ")", "throws", "IOException", "{", "KV", "<", "Receive", ",", "ErrorMapping", ">", "response", "=", "send", "(", "new", "DeleterRequest", "(", "topic", ",", "password", ")", ...
delete topic never used @param topic topic name @param password password @return number of partitions deleted @throws IOException if an I/O error
[ "delete", "topic", "never", "used" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/admin/AdminOperation.java#L64-L67
train
adyliu/jafka
src/main/java/io/jafka/message/Message.java
Message.payload
public ByteBuffer payload() { ByteBuffer payload = buffer.duplicate(); payload.position(headerSize(magic())); payload = payload.slice(); payload.limit(payloadSize()); payload.rewind(); return payload; }
java
public ByteBuffer payload() { ByteBuffer payload = buffer.duplicate(); payload.position(headerSize(magic())); payload = payload.slice(); payload.limit(payloadSize()); payload.rewind(); return payload; }
[ "public", "ByteBuffer", "payload", "(", ")", "{", "ByteBuffer", "payload", "=", "buffer", ".", "duplicate", "(", ")", ";", "payload", ".", "position", "(", "headerSize", "(", "magic", "(", ")", ")", ")", ";", "payload", "=", "payload", ".", "slice", "(...
get the real data without message header @return message data(without header)
[ "get", "the", "real", "data", "without", "message", "header" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/message/Message.java#L195-L202
train
adyliu/jafka
src/main/java/io/jafka/log/Log.java
Log.validateSegments
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()); } } } }
java
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()); } } } }
[ "private", "void", "validateSegments", "(", "List", "<", "LogSegment", ">", "segments", ")", "{", "synchronized", "(", "lock", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "segments", ".", "size", "(", ")", "-", "1", ";", "i", "++", ...
Check that the ranges and sizes add up, otherwise we have lost some data somewhere
[ "Check", "that", "the", "ranges", "and", "sizes", "add", "up", "otherwise", "we", "have", "lost", "some", "data", "somewhere" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/Log.java#L151-L162
train
adyliu/jafka
src/main/java/io/jafka/log/Log.java
Log.read
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); }
java
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); }
[ "public", "MessageSet", "read", "(", "long", "offset", ",", "int", "length", ")", "throws", "IOException", "{", "List", "<", "LogSegment", ">", "views", "=", "segments", ".", "getView", "(", ")", ";", "LogSegment", "found", "=", "findRange", "(", "views", ...
read messages beginning from offset @param offset next message offset @param length the max package size @return a MessageSet object with length data or empty @see MessageSet#Empty @throws IOException any exception
[ "read", "messages", "beginning", "from", "offset" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/Log.java#L203-L213
train
adyliu/jafka
src/main/java/io/jafka/log/Log.java
Log.flush
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()); } }
java
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()); } }
[ "public", "void", "flush", "(", ")", "throws", "IOException", "{", "if", "(", "unflushed", ".", "get", "(", ")", "==", "0", ")", "return", ";", "synchronized", "(", "lock", ")", "{", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "{", "...
Flush this log file to the physical disk @throws IOException file read error
[ "Flush", "this", "log", "file", "to", "the", "physical", "disk" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/Log.java#L308-L320
train
adyliu/jafka
src/main/java/io/jafka/log/Log.java
Log.findRange
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; }
java
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; }
[ "public", "static", "<", "T", "extends", "Range", ">", "T", "findRange", "(", "List", "<", "T", ">", "ranges", ",", "long", "value", ",", "int", "arraySize", ")", "{", "if", "(", "ranges", ".", "size", "(", ")", "<", "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 @param <T> Range type @param ranges data list @param value value in the list @param arraySize the max search index of the list @return search result of range TODO: This should move into SegmentList.scala
[ "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"...
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/Log.java#L334-L361
train
adyliu/jafka
src/main/java/io/jafka/log/Log.java
Log.nameFromOffset
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; }
java
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; }
[ "public", "static", "String", "nameFromOffset", "(", "long", "offset", ")", "{", "NumberFormat", "nf", "=", "NumberFormat", ".", "getInstance", "(", ")", ";", "nf", ".", "setMinimumIntegerDigits", "(", "20", ")", ";", "nf", ".", "setMaximumFractionDigits", "("...
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 @param offset offset value (padding with zero) @return filename with offset
[ "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" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/Log.java#L373-L379
train
adyliu/jafka
src/main/java/io/jafka/log/Log.java
Log.markDeletedWhile
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); } }
java
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); } }
[ "List", "<", "LogSegment", ">", "markDeletedWhile", "(", "LogSegmentFilter", "filter", ")", "throws", "IOException", "{", "synchronized", "(", "lock", ")", "{", "List", "<", "LogSegment", ">", "view", "=", "segments", ".", "getView", "(", ")", ";", "List", ...
Delete any log segments matching the given predicate function @throws IOException
[ "Delete", "any", "log", "segments", "matching", "the", "given", "predicate", "function" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/Log.java#L415-L442
train
adyliu/jafka
src/main/java/io/jafka/message/ByteBufferMessageSet.java
ByteBufferMessageSet.verifyMessageSize
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); } } }
java
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); } } }
[ "public", "void", "verifyMessageSize", "(", "int", "maxMessageSize", ")", "{", "Iterator", "<", "MessageAndOffset", ">", "shallowIter", "=", "internalIterator", "(", "true", ")", ";", "while", "(", "shallowIter", ".", "hasNext", "(", ")", ")", "{", "MessageAnd...
check max size of each message @param maxMessageSize the max size for each message
[ "check", "max", "size", "of", "each", "message" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/message/ByteBufferMessageSet.java#L206-L215
train
adyliu/jafka
src/main/java/io/jafka/network/SocketServer.java
SocketServer.close
public void close() { Closer.closeQuietly(acceptor); for (Processor processor : processors) { Closer.closeQuietly(processor); } }
java
public void close() { Closer.closeQuietly(acceptor); for (Processor processor : processors) { Closer.closeQuietly(processor); } }
[ "public", "void", "close", "(", ")", "{", "Closer", ".", "closeQuietly", "(", "acceptor", ")", ";", "for", "(", "Processor", "processor", ":", "processors", ")", "{", "Closer", ".", "closeQuietly", "(", "processor", ")", ";", "}", "}" ]
Shutdown the socket server
[ "Shutdown", "the", "socket", "server" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/network/SocketServer.java#L69-L74
train
adyliu/jafka
src/main/java/io/jafka/network/SocketServer.java
SocketServer.startup
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(); }
java
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(); }
[ "public", "void", "startup", "(", ")", "throws", "InterruptedException", "{", "final", "int", "maxCacheConnectionPerThread", "=", "serverConfig", ".", "getMaxConnections", "(", ")", "/", "processors", ".", "length", ";", "logger", ".", "debug", "(", "\"start {} Pr...
Start the socket server and waiting for finished @throws InterruptedException thread interrupted
[ "Start", "the", "socket", "server", "and", "waiting", "for", "finished" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/network/SocketServer.java#L81-L90
train
adyliu/jafka
src/main/java/io/jafka/utils/zookeeper/ZkUtils.java
ZkUtils.getChildrenParentMayNotExist
public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) { try { return zkClient.getChildren(path); } catch (ZkNoNodeException e) { return null; } }
java
public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) { try { return zkClient.getChildren(path); } catch (ZkNoNodeException e) { return null; } }
[ "public", "static", "List", "<", "String", ">", "getChildrenParentMayNotExist", "(", "ZkClient", "zkClient", ",", "String", "path", ")", "{", "try", "{", "return", "zkClient", ".", "getChildren", "(", "path", ")", ";", "}", "catch", "(", "ZkNoNodeException", ...
get children nodes name @param zkClient zkClient @param path full path @return children nodes name or null while path not exist
[ "get", "children", "nodes", "name" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/zookeeper/ZkUtils.java#L60-L66
train
adyliu/jafka
src/main/java/io/jafka/utils/zookeeper/ZkUtils.java
ZkUtils.getCluster
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; }
java
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; }
[ "public", "static", "Cluster", "getCluster", "(", "ZkClient", "zkClient", ")", "{", "Cluster", "cluster", "=", "new", "Cluster", "(", ")", ";", "List", "<", "String", ">", "nodes", "=", "getChildrenParentMayNotExist", "(", "zkClient", ",", "BrokerIdsPath", ")"...
read all brokers in the zookeeper @param zkClient zookeeper client @return all brokers
[ "read", "all", "brokers", "in", "the", "zookeeper" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/zookeeper/ZkUtils.java#L102-L110
train
adyliu/jafka
src/main/java/io/jafka/utils/zookeeper/ZkUtils.java
ZkUtils.getPartitionsForTopics
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; }
java
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; }
[ "public", "static", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "getPartitionsForTopics", "(", "ZkClient", "zkClient", ",", "Collection", "<", "String", ">", "topics", ")", "{", "Map", "<", "String", ",", "List", "<", "String", ">", ">", ...
read broker info for watching topics @param zkClient the zookeeper client @param topics topic names @return topic-&gt;(brokerid-0,brokerid-1...brokerid2-0,brokerid2-1...)
[ "read", "broker", "info", "for", "watching", "topics" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/zookeeper/ZkUtils.java#L125-L143
train
adyliu/jafka
src/main/java/io/jafka/utils/zookeeper/ZkUtils.java
ZkUtils.getConsumersPerTopic
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; }
java
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; }
[ "public", "static", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "getConsumersPerTopic", "(", "ZkClient", "zkClient", ",", "String", "group", ")", "{", "ZkGroupDirs", "dirs", "=", "new", "ZkGroupDirs", "(", "group", ")", ";", "List", "<", ...
get all consumers for the group @param zkClient the zookeeper client @param group the group name @return topic-&gt;(consumerIdStringA-0,consumerIdStringA-1...consumerIdStringB-0,consumerIdStringB-1)
[ "get", "all", "consumers", "for", "the", "group" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/zookeeper/ZkUtils.java#L152-L177
train
adyliu/jafka
src/main/java/io/jafka/utils/zookeeper/ZkUtils.java
ZkUtils.createEphemeralPath
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)); } }
java
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)); } }
[ "public", "static", "void", "createEphemeralPath", "(", "ZkClient", "zkClient", ",", "String", "path", ",", "String", "data", ")", "{", "try", "{", "zkClient", ".", "createEphemeral", "(", "path", ",", "Utils", ".", "getBytes", "(", "data", ")", ")", ";", ...
Create an ephemeral node with the given path and data. Create parents if necessary. @param zkClient client of zookeeper @param path node path of zookeeper @param data node data
[ "Create", "an", "ephemeral", "node", "with", "the", "given", "path", "and", "data", ".", "Create", "parents", "if", "necessary", "." ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/zookeeper/ZkUtils.java#L197-L204
train
adyliu/jafka
src/main/java/io/jafka/producer/ProducerPool.java
ProducerPool.addProducer
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); } }
java
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); } }
[ "public", "void", "addProducer", "(", "Broker", "broker", ")", "{", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "props", ".", "put", "(", "\"host\"", ",", "broker", ".", "host", ")", ";", "props", ".", "put", "(", "\"port\"", ",", ...
add a new producer, either synchronous or asynchronous, connecting to the specified broker @param broker broker to producer
[ "add", "a", "new", "producer", "either", "synchronous", "or", "asynchronous", "connecting", "to", "the", "specified", "broker" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/producer/ProducerPool.java#L117-L138
train
adyliu/jafka
src/main/java/io/jafka/producer/ProducerPool.java
ProducerPool.send
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); } } }
java
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); } } }
[ "public", "void", "send", "(", "ProducerPoolData", "<", "V", ">", "ppd", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"send message: \"", "+", "ppd", ")", ";", "}", "if", "(", "sync", ")", ...
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 @param ppd the producer pool request object
[ "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", "...
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/producer/ProducerPool.java#L147-L172
train
adyliu/jafka
src/main/java/io/jafka/producer/ProducerPool.java
ProducerPool.close
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(); } } }
java
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(); } } }
[ "public", "void", "close", "(", ")", "{", "logger", ".", "info", "(", "\"Closing all sync producers\"", ")", ";", "if", "(", "sync", ")", "{", "for", "(", "SyncProducer", "p", ":", "syncProducers", ".", "values", "(", ")", ")", "{", "p", ".", "close", ...
Closes all the producers in the pool
[ "Closes", "all", "the", "producers", "in", "the", "pool" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/producer/ProducerPool.java#L226-L238
train
adyliu/jafka
src/main/java/io/jafka/producer/ProducerPool.java
ProducerPool.getProducerPoolData
public ProducerPoolData<V> getProducerPoolData(String topic, Partition bidPid, List<V> data) { return new ProducerPoolData<V>(topic, bidPid, data); }
java
public ProducerPoolData<V> getProducerPoolData(String topic, Partition bidPid, List<V> data) { return new ProducerPoolData<V>(topic, bidPid, data); }
[ "public", "ProducerPoolData", "<", "V", ">", "getProducerPoolData", "(", "String", "topic", ",", "Partition", "bidPid", ",", "List", "<", "V", ">", "data", ")", "{", "return", "new", "ProducerPoolData", "<", "V", ">", "(", "topic", ",", "bidPid", ",", "d...
This constructs and returns the request object for the producer pool @param topic the topic to which the data should be published @param bidPid the broker id and partition id @param data the data to be published @return producer data of builder
[ "This", "constructs", "and", "returns", "the", "request", "object", "for", "the", "producer", "pool" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/producer/ProducerPool.java#L248-L250
train
adyliu/jafka
src/main/java/io/jafka/api/ProducerRequest.java
ProducerRequest.readFrom
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)); }
java
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)); }
[ "public", "static", "ProducerRequest", "readFrom", "(", "ByteBuffer", "buffer", ")", "{", "String", "topic", "=", "Utils", ".", "readShortString", "(", "buffer", ")", ";", "int", "partition", "=", "buffer", ".", "getInt", "(", ")", ";", "int", "messageSetSiz...
read a producer request from buffer @param buffer data buffer @return parsed producer request
[ "read", "a", "producer", "request", "from", "buffer" ]
cc14d2ed60c039b12d7b106bb5269ef21d0add7e
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/api/ProducerRequest.java#L57-L65
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/imap/commands/CommandTemplate.java
CommandTemplate.getExpectedMessage
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(); }
java
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(); }
[ "protected", "String", "getExpectedMessage", "(", ")", "{", "StringBuilder", "syntax", "=", "new", "StringBuilder", "(", "\"<tag> \"", ")", ";", "syntax", ".", "append", "(", "getName", "(", ")", ")", ";", "String", "args", "=", "getArgSyntax", "(", ")", "...
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. @return A message describing the command protocol format.
[ "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", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/imap/commands/CommandTemplate.java#L93-L104
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/ServerSetup.java
ServerSetup.createCopy
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; }
java
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; }
[ "public", "ServerSetup", "createCopy", "(", "String", "bindAddress", ")", "{", "ServerSetup", "setup", "=", "new", "ServerSetup", "(", "getPort", "(", ")", ",", "bindAddress", ",", "getProtocol", "(", ")", ")", ";", "setup", ".", "setServerStartupTimeout", "("...
Create a deep copy. @param bindAddress overwrites bind address when creating deep copy. @return a copy of the server setup configuration.
[ "Create", "a", "deep", "copy", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/ServerSetup.java#L300-L309
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/ServerSetup.java
ServerSetup.verbose
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; }
java
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; }
[ "public", "static", "ServerSetup", "[", "]", "verbose", "(", "ServerSetup", "[", "]", "serverSetups", ")", "{", "ServerSetup", "[", "]", "copies", "=", "new", "ServerSetup", "[", "serverSetups", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ...
Creates a copy with verbose mode enabled. @param serverSetups the server setups. @return copies of server setups with verbose mode enabled.
[ "Creates", "a", "copy", "with", "verbose", "mode", "enabled", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/ServerSetup.java#L317-L323
train
greenmail-mail-test/greenmail
greenmail-standalone/src/main/java/com/icegreen/greenmail/standalone/GreenMailStandaloneRunner.java
GreenMailStandaloneRunner.doRun
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(); } }
java
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(); } }
[ "public", "void", "doRun", "(", "Properties", "properties", ")", "{", "ServerSetup", "[", "]", "serverSetup", "=", "new", "PropertiesBasedServerSetupBuilder", "(", ")", ".", "build", "(", "properties", ")", ";", "if", "(", "serverSetup", ".", "length", "==", ...
Start and configure GreenMail using given properties. @param properties the properties such as System.getProperties()
[ "Start", "and", "configure", "GreenMail", "using", "given", "properties", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-standalone/src/main/java/com/icegreen/greenmail/standalone/GreenMailStandaloneRunner.java#L34-L47
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/mail/MailAddress.java
MailAddress.decodeStr
private String decodeStr(String str) { try { return MimeUtility.decodeText(str); } catch (UnsupportedEncodingException e) { return str; } }
java
private String decodeStr(String str) { try { return MimeUtility.decodeText(str); } catch (UnsupportedEncodingException e) { return str; } }
[ "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. @param str string to be decoded @return the decoded string, in case it contains non us-ascii characters; or the same string if it doesn't or the passed value in case of an UnsupportedEncodingException.
[ "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", "UnsupportedEncodin...
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/mail/MailAddress.java#L72-L78
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java
GreenMailUtil.copyStream
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(); }
java
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(); }
[ "public", "static", "void", "copyStream", "(", "final", "InputStream", "src", ",", "OutputStream", "dest", ")", "throws", "IOException", "{", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "1024", "]", ";", "int", "read", ";", "while", "(", "(", ...
Writes the content of an input stream to an output stream @throws IOException
[ "Writes", "the", "content", "of", "an", "input", "stream", "to", "an", "output", "stream" ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java#L56-L63
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java
GreenMailUtil.getLineCount
public static int getLineCount(String str) { if (null == str || str.isEmpty()) { return 0; } int count = 1; for (char c : str.toCharArray()) { if ('\n' == c) { count++; } } return count; }
java
public static int getLineCount(String str) { if (null == str || str.isEmpty()) { return 0; } int count = 1; for (char c : str.toCharArray()) { if ('\n' == c) { count++; } } return count; }
[ "public", "static", "int", "getLineCount", "(", "String", "str", ")", "{", "if", "(", "null", "==", "str", "||", "str", ".", "isEmpty", "(", ")", ")", "{", "return", "0", ";", "}", "int", "count", "=", "1", ";", "for", "(", "char", "c", ":", "s...
Counts the number of lines. @param str the input string @return Returns the number of lines terminated by '\n' in string
[ "Counts", "the", "number", "of", "lines", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java#L113-L124
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java
GreenMailUtil.sendTextEmail
public static void sendTextEmail(String to, String from, String subject, String msg, final ServerSetup setup) { sendMimeMessage(createTextEmail(to, from, subject, msg, setup)); }
java
public static void sendTextEmail(String to, String from, String subject, String msg, final ServerSetup setup) { sendMimeMessage(createTextEmail(to, from, subject, msg, setup)); }
[ "public", "static", "void", "sendTextEmail", "(", "String", "to", ",", "String", "from", ",", "String", "subject", ",", "String", "msg", ",", "final", "ServerSetup", "setup", ")", "{", "sendMimeMessage", "(", "createTextEmail", "(", "to", ",", "from", ",", ...
Sends a text message using given server setup for SMTP. @param to the to address. @param from the from address. @param subject the subject. @param msg the test message. @param setup the SMTP setup.
[ "Sends", "a", "text", "message", "using", "given", "server", "setup", "for", "SMTP", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java#L262-L264
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java
GreenMailUtil.sendMimeMessage
public static void sendMimeMessage(MimeMessage mimeMessage) { try { Transport.send(mimeMessage); } catch (MessagingException e) { throw new IllegalStateException("Can not send message " + mimeMessage, e); } }
java
public static void sendMimeMessage(MimeMessage mimeMessage) { try { Transport.send(mimeMessage); } catch (MessagingException e) { throw new IllegalStateException("Can not send message " + mimeMessage, e); } }
[ "public", "static", "void", "sendMimeMessage", "(", "MimeMessage", "mimeMessage", ")", "{", "try", "{", "Transport", ".", "send", "(", "mimeMessage", ")", ";", "}", "catch", "(", "MessagingException", "e", ")", "{", "throw", "new", "IllegalStateException", "("...
Send the message using the JavaMail session defined in the message @param mimeMessage Message to send
[ "Send", "the", "message", "using", "the", "JavaMail", "session", "defined", "in", "the", "message" ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java#L271-L277
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java
GreenMailUtil.sendMessageBody
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); } }
java
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); } }
[ "public", "static", "void", "sendMessageBody", "(", "String", "to", ",", "String", "from", ",", "String", "subject", ",", "Object", "body", ",", "String", "contentType", ",", "ServerSetup", "serverSetup", ")", "{", "try", "{", "Session", "smtpSession", "=", ...
Send the message with the given attributes and the given body using the specified SMTP settings @param to Destination address(es) @param from Sender address @param subject Message subject @param body Message content. May either be a MimeMultipart or another body that java mail recognizes @param contentType MIME content type of body @param serverSetup Server settings to use for connecting to the SMTP server
[ "Send", "the", "message", "with", "the", "given", "attributes", "and", "the", "given", "body", "using", "the", "specified", "SMTP", "settings" ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java#L289-L302
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java
GreenMailUtil.createMultipartWithAttachment
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); } }
java
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); } }
[ "public", "static", "MimeMultipart", "createMultipartWithAttachment", "(", "String", "msg", ",", "final", "byte", "[", "]", "attachment", ",", "final", "String", "contentType", ",", "final", "String", "filename", ",", "String", "description", ")", "{", "try", "{...
Create new multipart with a text part and an attachment @param msg Message text @param attachment Attachment data @param contentType MIME content type of body @param filename File name of the attachment @param description Description of the attachment @return New multipart
[ "Create", "new", "multipart", "with", "a", "text", "part", "and", "an", "attachment" ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java#L322-L364
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java
GreenMailUtil.getSession
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); }
java
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); }
[ "public", "static", "Session", "getSession", "(", "final", "ServerSetup", "setup", ",", "Properties", "mailProps", ")", "{", "Properties", "props", "=", "setup", ".", "configureJavaMailSessionProperties", "(", "mailProps", ",", "false", ")", ";", "log", ".", "de...
Gets a JavaMail Session for given server type such as IMAP and additional props for JavaMail. @param setup the setup type, such as <code>ServerSetup.IMAP</code> @param mailProps additional mail properties. @return the JavaMail session.
[ "Gets", "a", "JavaMail", "Session", "for", "given", "server", "type", "such", "as", "IMAP", "and", "additional", "props", "for", "JavaMail", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java#L377-L383
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java
GreenMailUtil.setQuota
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); } }
java
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); } }
[ "public", "static", "void", "setQuota", "(", "final", "GreenMailUser", "user", ",", "final", "Quota", "quota", ")", "{", "Session", "session", "=", "GreenMailUtil", ".", "getSession", "(", "ServerSetupTest", ".", "IMAP", ")", ";", "try", "{", "Store", "store...
Sets a quota for a users. @param user the user. @param quota the quota.
[ "Sets", "a", "quota", "for", "a", "users", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java#L391-L405
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/user/UserManager.java
UserManager.hasUser
public boolean hasUser(String userId) { String normalized = normalizerUserName(userId); return loginToUser.containsKey(normalized) || emailToUser.containsKey(normalized); }
java
public boolean hasUser(String userId) { String normalized = normalizerUserName(userId); return loginToUser.containsKey(normalized) || emailToUser.containsKey(normalized); }
[ "public", "boolean", "hasUser", "(", "String", "userId", ")", "{", "String", "normalized", "=", "normalizerUserName", "(", "userId", ")", ";", "return", "loginToUser", ".", "containsKey", "(", "normalized", ")", "||", "emailToUser", ".", "containsKey", "(", "n...
Checks if user exists. @param userId the user id, which can be an email or the login. @return true, if user exists.
[ "Checks", "if", "user", "exists", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/user/UserManager.java#L110-L113
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/server/AbstractServer.java
AbstractServer.closeServerSocket
protected void closeServerSocket() { // Close server socket, we do not accept new requests anymore. // This also terminates the server thread if blocking on socket.accept. if (null != serverSocket) { try { if (!serverSocket.isClosed()) { serverSocket.close(); if (log.isTraceEnabled()) { log.trace("Closed server socket " + serverSocket + "/ref=" + Integer.toHexString(System.identityHashCode(serverSocket)) + " for " + getName()); } } } catch (IOException e) { throw new IllegalStateException("Failed to successfully quit server " + getName(), e); } } }
java
protected void closeServerSocket() { // Close server socket, we do not accept new requests anymore. // This also terminates the server thread if blocking on socket.accept. if (null != serverSocket) { try { if (!serverSocket.isClosed()) { serverSocket.close(); if (log.isTraceEnabled()) { log.trace("Closed server socket " + serverSocket + "/ref=" + Integer.toHexString(System.identityHashCode(serverSocket)) + " for " + getName()); } } } catch (IOException e) { throw new IllegalStateException("Failed to successfully quit server " + getName(), e); } } }
[ "protected", "void", "closeServerSocket", "(", ")", "{", "// Close server socket, we do not accept new requests anymore.", "// This also terminates the server thread if blocking on socket.accept.", "if", "(", "null", "!=", "serverSocket", ")", "{", "try", "{", "if", "(", "!", ...
Closes the server socket.
[ "Closes", "the", "server", "socket", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/server/AbstractServer.java#L126-L143
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/server/AbstractServer.java
AbstractServer.quit
protected synchronized void quit() { log.debug("Stopping {}", getName()); closeServerSocket(); // Close all handlers. Handler threads terminate if run loop exits synchronized (handlers) { for (ProtocolHandler handler : handlers) { handler.close(); } handlers.clear(); } log.debug("Stopped {}", getName()); }
java
protected synchronized void quit() { log.debug("Stopping {}", getName()); closeServerSocket(); // Close all handlers. Handler threads terminate if run loop exits synchronized (handlers) { for (ProtocolHandler handler : handlers) { handler.close(); } handlers.clear(); } log.debug("Stopped {}", getName()); }
[ "protected", "synchronized", "void", "quit", "(", ")", "{", "log", ".", "debug", "(", "\"Stopping {}\"", ",", "getName", "(", ")", ")", ";", "closeServerSocket", "(", ")", ";", "// Close all handlers. Handler threads terminate if run loop exits", "synchronized", "(", ...
Quits server by closing server socket and closing client socket handlers.
[ "Quits", "server", "by", "closing", "server", "socket", "and", "closing", "client", "socket", "handlers", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/server/AbstractServer.java#L186-L198
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/server/AbstractServer.java
AbstractServer.stopService
@Override public final synchronized void stopService(long millis) { running = false; try { if (keepRunning) { keepRunning = false; interrupt(); quit(); if (0L == millis) { join(); } else { join(millis); } } } catch (InterruptedException e) { //its possible that the thread exits between the lines keepRunning=false and interrupt above log.warn("Got interrupted while stopping {}", this, e); Thread.currentThread().interrupt(); } }
java
@Override public final synchronized void stopService(long millis) { running = false; try { if (keepRunning) { keepRunning = false; interrupt(); quit(); if (0L == millis) { join(); } else { join(millis); } } } catch (InterruptedException e) { //its possible that the thread exits between the lines keepRunning=false and interrupt above log.warn("Got interrupted while stopping {}", this, e); Thread.currentThread().interrupt(); } }
[ "@", "Override", "public", "final", "synchronized", "void", "stopService", "(", "long", "millis", ")", "{", "running", "=", "false", ";", "try", "{", "if", "(", "keepRunning", ")", "{", "keepRunning", "=", "false", ";", "interrupt", "(", ")", ";", "quit"...
Stops the service. If a timeout is given and the service has still not gracefully been stopped after timeout ms the service is stopped by force. @param millis value in ms
[ "Stops", "the", "service", ".", "If", "a", "timeout", "is", "given", "and", "the", "service", "has", "still", "not", "gracefully", "been", "stopped", "after", "timeout", "ms", "the", "service", "is", "stopped", "by", "force", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/server/AbstractServer.java#L255-L275
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/store/SimpleMessageAttributes.java
SimpleMessageAttributes.getSentDate
private static Date getSentDate(MimeMessage msg, Date defaultVal) { if (msg == null) { return defaultVal; } try { Date sentDate = msg.getSentDate(); if (sentDate == null) { return defaultVal; } else { return sentDate; } } catch (MessagingException me) { return new Date(); } }
java
private static Date getSentDate(MimeMessage msg, Date defaultVal) { if (msg == null) { return defaultVal; } try { Date sentDate = msg.getSentDate(); if (sentDate == null) { return defaultVal; } else { return sentDate; } } catch (MessagingException me) { return new Date(); } }
[ "private", "static", "Date", "getSentDate", "(", "MimeMessage", "msg", ",", "Date", "defaultVal", ")", "{", "if", "(", "msg", "==", "null", ")", "{", "return", "defaultVal", ";", "}", "try", "{", "Date", "sentDate", "=", "msg", ".", "getSentDate", "(", ...
Compute "sent" date @param msg Message to take sent date from. May be null to use default @param defaultVal Default if sent date is not present @return Sent date or now if no date could be found
[ "Compute", "sent", "date" ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/store/SimpleMessageAttributes.java#L102-L116
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/store/SimpleMessageAttributes.java
SimpleMessageAttributes.parseEnvelope
private String parseEnvelope() { List<String> response = new ArrayList<>(); //1. Date --------------- response.add(LB + Q + sentDateEnvelopeString + Q + SP); //2. Subject --------------- if (subject != null && (subject.length() != 0)) { response.add(Q + escapeHeader(subject) + Q + SP); } else { response.add(NIL + SP); } //3. From --------------- addAddressToEnvelopeIfAvailable(from, response); response.add(SP); //4. Sender --------------- addAddressToEnvelopeIfAvailableWithNetscapeFeature(sender, response); response.add(SP); addAddressToEnvelopeIfAvailableWithNetscapeFeature(replyTo, response); response.add(SP); addAddressToEnvelopeIfAvailable(to, response); response.add(SP); addAddressToEnvelopeIfAvailable(cc, response); response.add(SP); addAddressToEnvelopeIfAvailable(bcc, response); response.add(SP); if (inReplyTo != null && inReplyTo.length > 0) { response.add(inReplyTo[0]); } else { response.add(NIL); } response.add(SP); if (messageID != null && messageID.length > 0) { messageID[0] = escapeHeader(messageID[0]); response.add(Q + messageID[0] + Q); } else { response.add(NIL); } response.add(RB); StringBuilder buf = new StringBuilder(16 * response.size()); for (String aResponse : response) { buf.append(aResponse); } return buf.toString(); }
java
private String parseEnvelope() { List<String> response = new ArrayList<>(); //1. Date --------------- response.add(LB + Q + sentDateEnvelopeString + Q + SP); //2. Subject --------------- if (subject != null && (subject.length() != 0)) { response.add(Q + escapeHeader(subject) + Q + SP); } else { response.add(NIL + SP); } //3. From --------------- addAddressToEnvelopeIfAvailable(from, response); response.add(SP); //4. Sender --------------- addAddressToEnvelopeIfAvailableWithNetscapeFeature(sender, response); response.add(SP); addAddressToEnvelopeIfAvailableWithNetscapeFeature(replyTo, response); response.add(SP); addAddressToEnvelopeIfAvailable(to, response); response.add(SP); addAddressToEnvelopeIfAvailable(cc, response); response.add(SP); addAddressToEnvelopeIfAvailable(bcc, response); response.add(SP); if (inReplyTo != null && inReplyTo.length > 0) { response.add(inReplyTo[0]); } else { response.add(NIL); } response.add(SP); if (messageID != null && messageID.length > 0) { messageID[0] = escapeHeader(messageID[0]); response.add(Q + messageID[0] + Q); } else { response.add(NIL); } response.add(RB); StringBuilder buf = new StringBuilder(16 * response.size()); for (String aResponse : response) { buf.append(aResponse); } return buf.toString(); }
[ "private", "String", "parseEnvelope", "(", ")", "{", "List", "<", "String", ">", "response", "=", "new", "ArrayList", "<>", "(", ")", ";", "//1. Date ---------------\r", "response", ".", "add", "(", "LB", "+", "Q", "+", "sentDateEnvelopeString", "+", "Q", ...
Builds IMAP envelope String from pre-parsed data.
[ "Builds", "IMAP", "envelope", "String", "from", "pre", "-", "parsed", "data", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/store/SimpleMessageAttributes.java#L276-L320
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/store/SimpleMessageAttributes.java
SimpleMessageAttributes.parseAddress
private String parseAddress(String address) { try { StringBuilder buf = new StringBuilder(); InternetAddress[] netAddrs = InternetAddress.parseHeader(address, false); for (InternetAddress netAddr : netAddrs) { if (buf.length() > 0) { buf.append(SP); } buf.append(LB); String personal = netAddr.getPersonal(); if (personal != null && (personal.length() != 0)) { buf.append(Q).append(personal).append(Q); } else { buf.append(NIL); } buf.append(SP); buf.append(NIL); // should add route-addr buf.append(SP); try { // Remove quotes to avoid double quoting MailAddress mailAddr = new MailAddress(netAddr.getAddress().replaceAll("\"", "\\\\\"")); buf.append(Q).append(mailAddr.getUser()).append(Q); buf.append(SP); buf.append(Q).append(mailAddr.getHost()).append(Q); } catch (Exception pe) { buf.append(NIL + SP + NIL); } buf.append(RB); } return buf.toString(); } catch (AddressException e) { throw new RuntimeException("Failed to parse address: " + address, e); } }
java
private String parseAddress(String address) { try { StringBuilder buf = new StringBuilder(); InternetAddress[] netAddrs = InternetAddress.parseHeader(address, false); for (InternetAddress netAddr : netAddrs) { if (buf.length() > 0) { buf.append(SP); } buf.append(LB); String personal = netAddr.getPersonal(); if (personal != null && (personal.length() != 0)) { buf.append(Q).append(personal).append(Q); } else { buf.append(NIL); } buf.append(SP); buf.append(NIL); // should add route-addr buf.append(SP); try { // Remove quotes to avoid double quoting MailAddress mailAddr = new MailAddress(netAddr.getAddress().replaceAll("\"", "\\\\\"")); buf.append(Q).append(mailAddr.getUser()).append(Q); buf.append(SP); buf.append(Q).append(mailAddr.getHost()).append(Q); } catch (Exception pe) { buf.append(NIL + SP + NIL); } buf.append(RB); } return buf.toString(); } catch (AddressException e) { throw new RuntimeException("Failed to parse address: " + address, e); } }
[ "private", "String", "parseAddress", "(", "String", "address", ")", "{", "try", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", ")", ";", "InternetAddress", "[", "]", "netAddrs", "=", "InternetAddress", ".", "parseHeader", "(", "address", ",", ...
Parses a String email address to an IMAP address string.
[ "Parses", "a", "String", "email", "address", "to", "an", "IMAP", "address", "string", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/store/SimpleMessageAttributes.java#L361-L397
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/store/SimpleMessageAttributes.java
SimpleMessageAttributes.decodeContentType
void decodeContentType(String rawLine) { int slash = rawLine.indexOf('/'); if (slash == -1) { // if (DEBUG) getLogger().debug("decoding ... no slash found"); return; } else { primaryType = rawLine.substring(0, slash).trim(); } int semicolon = rawLine.indexOf(';'); if (semicolon == -1) { // if (DEBUG) getLogger().debug("decoding ... no semicolon found"); secondaryType = rawLine.substring(slash + 1).trim(); return; } // have parameters secondaryType = rawLine.substring(slash + 1, semicolon).trim(); Header h = new Header(rawLine); parameters = h.getParams(); }
java
void decodeContentType(String rawLine) { int slash = rawLine.indexOf('/'); if (slash == -1) { // if (DEBUG) getLogger().debug("decoding ... no slash found"); return; } else { primaryType = rawLine.substring(0, slash).trim(); } int semicolon = rawLine.indexOf(';'); if (semicolon == -1) { // if (DEBUG) getLogger().debug("decoding ... no semicolon found"); secondaryType = rawLine.substring(slash + 1).trim(); return; } // have parameters secondaryType = rawLine.substring(slash + 1, semicolon).trim(); Header h = new Header(rawLine); parameters = h.getParams(); }
[ "void", "decodeContentType", "(", "String", "rawLine", ")", "{", "int", "slash", "=", "rawLine", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "slash", "==", "-", "1", ")", "{", "// if (DEBUG) getLogger().debug(\"decoding ... no slash found\");\r"...
Decode a content Type header line into types and parameters pairs
[ "Decode", "a", "content", "Type", "header", "line", "into", "types", "and", "parameters", "pairs" ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/store/SimpleMessageAttributes.java#L402-L420
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/configuration/ConfiguredGreenMail.java
ConfiguredGreenMail.doConfigure
protected void doConfigure() { if (config != null) { for (UserBean user : config.getUsersToCreate()) { setUser(user.getEmail(), user.getLogin(), user.getPassword()); } getManagers().getUserManager().setAuthRequired(!config.isAuthenticationDisabled()); } }
java
protected void doConfigure() { if (config != null) { for (UserBean user : config.getUsersToCreate()) { setUser(user.getEmail(), user.getLogin(), user.getPassword()); } getManagers().getUserManager().setAuthRequired(!config.isAuthenticationDisabled()); } }
[ "protected", "void", "doConfigure", "(", ")", "{", "if", "(", "config", "!=", "null", ")", "{", "for", "(", "UserBean", "user", ":", "config", ".", "getUsersToCreate", "(", ")", ")", "{", "setUser", "(", "user", ".", "getEmail", "(", ")", ",", "user"...
This method can be used by child classes to apply the configuration that is stored in config.
[ "This", "method", "can", "be", "used", "by", "child", "classes", "to", "apply", "the", "configuration", "that", "is", "stored", "in", "config", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/configuration/ConfiguredGreenMail.java#L20-L27
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/InternetPrintWriter.java
InternetPrintWriter.createForEncoding
public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) { return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush); }
java
public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) { return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush); }
[ "public", "static", "InternetPrintWriter", "createForEncoding", "(", "OutputStream", "outputStream", ",", "boolean", "autoFlush", ",", "Charset", "charset", ")", "{", "return", "new", "InternetPrintWriter", "(", "new", "OutputStreamWriter", "(", "outputStream", ",", "...
Creates a new InternetPrintWriter for given charset encoding. @param outputStream the wrapped output stream. @param charset the charset. @return a new InternetPrintWriter.
[ "Creates", "a", "new", "InternetPrintWriter", "for", "given", "charset", "encoding", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/InternetPrintWriter.java#L79-L81
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMail.java
GreenMail.createServices
protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) { Map<String, AbstractServer> srvc = new HashMap<>(); for (ServerSetup setup : config) { if (srvc.containsKey(setup.getProtocol())) { throw new IllegalArgumentException("Server '" + setup.getProtocol() + "' was found at least twice in the array"); } final String protocol = setup.getProtocol(); if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) { srvc.put(protocol, new SmtpServer(setup, mgr)); } else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) { srvc.put(protocol, new Pop3Server(setup, mgr)); } else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) { srvc.put(protocol, new ImapServer(setup, mgr)); } } return srvc; }
java
protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) { Map<String, AbstractServer> srvc = new HashMap<>(); for (ServerSetup setup : config) { if (srvc.containsKey(setup.getProtocol())) { throw new IllegalArgumentException("Server '" + setup.getProtocol() + "' was found at least twice in the array"); } final String protocol = setup.getProtocol(); if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) { srvc.put(protocol, new SmtpServer(setup, mgr)); } else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) { srvc.put(protocol, new Pop3Server(setup, mgr)); } else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) { srvc.put(protocol, new ImapServer(setup, mgr)); } } return srvc; }
[ "protected", "Map", "<", "String", ",", "AbstractServer", ">", "createServices", "(", "ServerSetup", "[", "]", "config", ",", "Managers", "mgr", ")", "{", "Map", "<", "String", ",", "AbstractServer", ">", "srvc", "=", "new", "HashMap", "<>", "(", ")", ";...
Create the required services according to the server setup @param config Service configuration @return Services map
[ "Create", "the", "required", "services", "according", "to", "the", "server", "setup" ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMail.java#L138-L154
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/imap/ImapResponse.java
ImapResponse.okResponse
public void okResponse(String responseCode, String message) { untagged(); message(OK); responseCode(responseCode); message(message); end(); }
java
public void okResponse(String responseCode, String message) { untagged(); message(OK); responseCode(responseCode); message(message); end(); }
[ "public", "void", "okResponse", "(", "String", "responseCode", ",", "String", "message", ")", "{", "untagged", "(", ")", ";", "message", "(", "OK", ")", ";", "responseCode", "(", "responseCode", ")", ";", "message", "(", "message", ")", ";", "end", "(", ...
Writes an untagged OK response, with the supplied response code, and an optional message. @param responseCode The response code, included in []. @param message The message to follow the []
[ "Writes", "an", "untagged", "OK", "response", "with", "the", "supplied", "response", "code", "and", "an", "optional", "message", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/imap/ImapResponse.java#L129-L135
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/imap/ImapHandler.java
ImapHandler.close
@Override public void close() { // Use monitor to avoid race between external close and handler thread run() synchronized (closeMonitor) { // Close and clear streams, sockets etc. if (socket != null) { try { // Terminates thread blocking on socket read // and automatically closed depending streams socket.close(); } catch (IOException e) { log.warn("Can not close socket", e); } finally { socket = null; } } // Clear user data session = null; response = null; } }
java
@Override public void close() { // Use monitor to avoid race between external close and handler thread run() synchronized (closeMonitor) { // Close and clear streams, sockets etc. if (socket != null) { try { // Terminates thread blocking on socket read // and automatically closed depending streams socket.close(); } catch (IOException e) { log.warn("Can not close socket", e); } finally { socket = null; } } // Clear user data session = null; response = null; } }
[ "@", "Override", "public", "void", "close", "(", ")", "{", "// Use monitor to avoid race between external close and handler thread run()\r", "synchronized", "(", "closeMonitor", ")", "{", "// Close and clear streams, sockets etc.\r", "if", "(", "socket", "!=", "null", ")", ...
Resets the handler data to a basic state.
[ "Resets", "the", "handler", "data", "to", "a", "basic", "state", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/imap/ImapHandler.java#L85-L106
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/EncodingUtil.java
EncodingUtil.toStream
public static InputStream toStream(String content, Charset charset) { byte[] bytes = content.getBytes(charset); return new ByteArrayInputStream(bytes); }
java
public static InputStream toStream(String content, Charset charset) { byte[] bytes = content.getBytes(charset); return new ByteArrayInputStream(bytes); }
[ "public", "static", "InputStream", "toStream", "(", "String", "content", ",", "Charset", "charset", ")", "{", "byte", "[", "]", "bytes", "=", "content", ".", "getBytes", "(", "charset", ")", ";", "return", "new", "ByteArrayInputStream", "(", "bytes", ")", ...
Converts the string of given content to an input stream. @param content the string content. @param charset the charset for conversion. @return the stream (should be closed by invoker).
[ "Converts", "the", "string", "of", "given", "content", "to", "an", "input", "stream", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/EncodingUtil.java#L33-L36
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/configuration/PropertiesBasedGreenMailConfigurationBuilder.java
PropertiesBasedGreenMailConfigurationBuilder.build
public GreenMailConfiguration build(Properties properties) { GreenMailConfiguration configuration = new GreenMailConfiguration(); String usersParam = properties.getProperty(GREENMAIL_USERS); if (null != usersParam) { String[] usersArray = usersParam.split(","); for (String user : usersArray) { extractAndAddUser(configuration, user); } } String disabledAuthentication = properties.getProperty(GREENMAIL_AUTH_DISABLED); if (null != disabledAuthentication) { configuration.withDisabledAuthentication(); } return configuration; }
java
public GreenMailConfiguration build(Properties properties) { GreenMailConfiguration configuration = new GreenMailConfiguration(); String usersParam = properties.getProperty(GREENMAIL_USERS); if (null != usersParam) { String[] usersArray = usersParam.split(","); for (String user : usersArray) { extractAndAddUser(configuration, user); } } String disabledAuthentication = properties.getProperty(GREENMAIL_AUTH_DISABLED); if (null != disabledAuthentication) { configuration.withDisabledAuthentication(); } return configuration; }
[ "public", "GreenMailConfiguration", "build", "(", "Properties", "properties", ")", "{", "GreenMailConfiguration", "configuration", "=", "new", "GreenMailConfiguration", "(", ")", ";", "String", "usersParam", "=", "properties", ".", "getProperty", "(", "GREENMAIL_USERS",...
Builds a configuration object based on given properties. @param properties the properties. @return a configuration and never null.
[ "Builds", "a", "configuration", "object", "based", "on", "given", "properties", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/configuration/PropertiesBasedGreenMailConfigurationBuilder.java#L36-L50
train
greenmail-mail-test/greenmail
greenmail-spring/src/main/java/com/icegreen/greenmail/spring/GreenMailBean.java
GreenMailBean.createServerSetup
private ServerSetup[] createServerSetup() { List<ServerSetup> setups = new ArrayList<>(); if (smtpProtocol) { smtpServerSetup = createTestServerSetup(ServerSetup.SMTP); setups.add(smtpServerSetup); } if (smtpsProtocol) { smtpsServerSetup = createTestServerSetup(ServerSetup.SMTPS); setups.add(smtpsServerSetup); } if (pop3Protocol) { setups.add(createTestServerSetup(ServerSetup.POP3)); } if (pop3sProtocol) { setups.add(createTestServerSetup(ServerSetup.POP3S)); } if (imapProtocol) { setups.add(createTestServerSetup(ServerSetup.IMAP)); } if (imapsProtocol) { setups.add(createTestServerSetup(ServerSetup.IMAPS)); } return setups.toArray(new ServerSetup[setups.size()]); }
java
private ServerSetup[] createServerSetup() { List<ServerSetup> setups = new ArrayList<>(); if (smtpProtocol) { smtpServerSetup = createTestServerSetup(ServerSetup.SMTP); setups.add(smtpServerSetup); } if (smtpsProtocol) { smtpsServerSetup = createTestServerSetup(ServerSetup.SMTPS); setups.add(smtpsServerSetup); } if (pop3Protocol) { setups.add(createTestServerSetup(ServerSetup.POP3)); } if (pop3sProtocol) { setups.add(createTestServerSetup(ServerSetup.POP3S)); } if (imapProtocol) { setups.add(createTestServerSetup(ServerSetup.IMAP)); } if (imapsProtocol) { setups.add(createTestServerSetup(ServerSetup.IMAPS)); } return setups.toArray(new ServerSetup[setups.size()]); }
[ "private", "ServerSetup", "[", "]", "createServerSetup", "(", ")", "{", "List", "<", "ServerSetup", ">", "setups", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "smtpProtocol", ")", "{", "smtpServerSetup", "=", "createTestServerSetup", "(", "Serve...
Creates the server setup, depending on the protocol flags. @return the configured server setups.
[ "Creates", "the", "server", "setup", "depending", "on", "the", "protocol", "flags", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-spring/src/main/java/com/icegreen/greenmail/spring/GreenMailBean.java#L102-L125
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/imap/commands/CommandParser.java
CommandParser.tag
public String tag(ImapRequestLineReader request) throws ProtocolException { CharacterValidator validator = new TagCharValidator(); return consumeWord(request, validator); }
java
public String tag(ImapRequestLineReader request) throws ProtocolException { CharacterValidator validator = new TagCharValidator(); return consumeWord(request, validator); }
[ "public", "String", "tag", "(", "ImapRequestLineReader", "request", ")", "throws", "ProtocolException", "{", "CharacterValidator", "validator", "=", "new", "TagCharValidator", "(", ")", ";", "return", "consumeWord", "(", "request", ",", "validator", ")", ";", "}" ...
Reads a command "tag" from the request.
[ "Reads", "a", "command", "tag", "from", "the", "request", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/imap/commands/CommandParser.java#L47-L50
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/imap/commands/CommandParser.java
CommandParser.astring
public String astring(ImapRequestLineReader request) throws ProtocolException { char next = request.nextWordChar(); switch (next) { case '"': return consumeQuoted(request); case '{': return consumeLiteral(request); default: return atom(request); } }
java
public String astring(ImapRequestLineReader request) throws ProtocolException { char next = request.nextWordChar(); switch (next) { case '"': return consumeQuoted(request); case '{': return consumeLiteral(request); default: return atom(request); } }
[ "public", "String", "astring", "(", "ImapRequestLineReader", "request", ")", "throws", "ProtocolException", "{", "char", "next", "=", "request", ".", "nextWordChar", "(", ")", ";", "switch", "(", "next", ")", "{", "case", "'", "'", ":", "return", "consumeQuo...
Reads an argument of type "astring" from the request.
[ "Reads", "an", "argument", "of", "type", "astring", "from", "the", "request", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/imap/commands/CommandParser.java#L55-L65
train
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/imap/commands/CommandParser.java
CommandParser.nstring
public String nstring(ImapRequestLineReader request) throws ProtocolException { char next = request.nextWordChar(); switch (next) { case '"': return consumeQuoted(request); case '{': return consumeLiteral(request); default: String value = atom(request); if ("NIL".equals(value)) { return null; } else { throw new ProtocolException("Invalid nstring value: valid values are '\"...\"', '{12} CRLF *CHAR8', and 'NIL'."); } } }
java
public String nstring(ImapRequestLineReader request) throws ProtocolException { char next = request.nextWordChar(); switch (next) { case '"': return consumeQuoted(request); case '{': return consumeLiteral(request); default: String value = atom(request); if ("NIL".equals(value)) { return null; } else { throw new ProtocolException("Invalid nstring value: valid values are '\"...\"', '{12} CRLF *CHAR8', and 'NIL'."); } } }
[ "public", "String", "nstring", "(", "ImapRequestLineReader", "request", ")", "throws", "ProtocolException", "{", "char", "next", "=", "request", ".", "nextWordChar", "(", ")", ";", "switch", "(", "next", ")", "{", "case", "'", "'", ":", "return", "consumeQuo...
Reads an argument of type "nstring" from the request.
[ "Reads", "an", "argument", "of", "type", "nstring", "from", "the", "request", "." ]
6d19a62233d1ef6fedbbd1f6fdde2d28e713834a
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/imap/commands/CommandParser.java#L70-L85
train