id int32 0 165k | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
160,400 | crawljax/crawljax | core/src/main/java/com/crawljax/condition/JavaScriptCondition.java | JavaScriptCondition.check | @Override
public boolean check(EmbeddedBrowser browser) {
String js =
"try{ if(" + expression + "){return '1';}else{" + "return '0';}}catch(e){"
+ " return '0';}";
try {
Object object = browser.executeJavaScript(js);
if (object == null) {
return false;
}
return object.toString().equals("1");
} catch (CrawljaxException e) {
// Exception is caught, check failed so return false;
return false;
}
} | java | @Override
public boolean check(EmbeddedBrowser browser) {
String js =
"try{ if(" + expression + "){return '1';}else{" + "return '0';}}catch(e){"
+ " return '0';}";
try {
Object object = browser.executeJavaScript(js);
if (object == null) {
return false;
}
return object.toString().equals("1");
} catch (CrawljaxException e) {
// Exception is caught, check failed so return false;
return false;
}
} | [
"@",
"Override",
"public",
"boolean",
"check",
"(",
"EmbeddedBrowser",
"browser",
")",
"{",
"String",
"js",
"=",
"\"try{ if(\"",
"+",
"expression",
"+",
"\"){return '1';}else{\"",
"+",
"\"return '0';}}catch(e){\"",
"+",
"\" return '0';}\"",
";",
"try",
"{",
"Object"... | Check invariant.
@param browser The browser.
@return Whether the condition is satisfied or <code>false</code> when it it isn't or a
{@link CrawljaxException} occurs. | [
"Check",
"invariant",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/condition/JavaScriptCondition.java#L34-L49 |
160,401 | crawljax/crawljax | core/src/main/java/com/crawljax/util/XMLObject.java | XMLObject.objectToXML | public static void objectToXML(Object object, String fileName) throws FileNotFoundException {
FileOutputStream fo = new FileOutputStream(fileName);
XMLEncoder encoder = new XMLEncoder(fo);
encoder.writeObject(object);
encoder.close();
} | java | public static void objectToXML(Object object, String fileName) throws FileNotFoundException {
FileOutputStream fo = new FileOutputStream(fileName);
XMLEncoder encoder = new XMLEncoder(fo);
encoder.writeObject(object);
encoder.close();
} | [
"public",
"static",
"void",
"objectToXML",
"(",
"Object",
"object",
",",
"String",
"fileName",
")",
"throws",
"FileNotFoundException",
"{",
"FileOutputStream",
"fo",
"=",
"new",
"FileOutputStream",
"(",
"fileName",
")",
";",
"XMLEncoder",
"encoder",
"=",
"new",
... | Converts an object to an XML file.
@param object The object to convert.
@param fileName The filename where to save it to.
@throws FileNotFoundException On error. | [
"Converts",
"an",
"object",
"to",
"an",
"XML",
"file",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/XMLObject.java#L25-L30 |
160,402 | crawljax/crawljax | core/src/main/java/com/crawljax/util/XMLObject.java | XMLObject.xmlToObject | public static Object xmlToObject(String fileName) throws FileNotFoundException {
FileInputStream fi = new FileInputStream(fileName);
XMLDecoder decoder = new XMLDecoder(fi);
Object object = decoder.readObject();
decoder.close();
return object;
} | java | public static Object xmlToObject(String fileName) throws FileNotFoundException {
FileInputStream fi = new FileInputStream(fileName);
XMLDecoder decoder = new XMLDecoder(fi);
Object object = decoder.readObject();
decoder.close();
return object;
} | [
"public",
"static",
"Object",
"xmlToObject",
"(",
"String",
"fileName",
")",
"throws",
"FileNotFoundException",
"{",
"FileInputStream",
"fi",
"=",
"new",
"FileInputStream",
"(",
"fileName",
")",
";",
"XMLDecoder",
"decoder",
"=",
"new",
"XMLDecoder",
"(",
"fi",
... | Converts an XML file to an object.
@param fileName The filename where to save it to.
@return The object.
@throws FileNotFoundException On error. | [
"Converts",
"an",
"XML",
"file",
"to",
"an",
"object",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/XMLObject.java#L39-L45 |
160,403 | crawljax/crawljax | core/src/main/java/com/crawljax/core/state/Identification.java | Identification.getWebDriverBy | public By getWebDriverBy() {
switch (how) {
case name:
return By.name(this.value);
case xpath:
// Work around HLWK driver bug
return By.xpath(this.value.replaceAll("/BODY\\[1\\]/", "/BODY/"));
case id:
return By.id(this.value);
case tag:
return By.tagName(this.value);
case text:
return By.linkText(this.value);
case partialText:
return By.partialLinkText(this.value);
default:
return null;
}
} | java | public By getWebDriverBy() {
switch (how) {
case name:
return By.name(this.value);
case xpath:
// Work around HLWK driver bug
return By.xpath(this.value.replaceAll("/BODY\\[1\\]/", "/BODY/"));
case id:
return By.id(this.value);
case tag:
return By.tagName(this.value);
case text:
return By.linkText(this.value);
case partialText:
return By.partialLinkText(this.value);
default:
return null;
}
} | [
"public",
"By",
"getWebDriverBy",
"(",
")",
"{",
"switch",
"(",
"how",
")",
"{",
"case",
"name",
":",
"return",
"By",
".",
"name",
"(",
"this",
".",
"value",
")",
";",
"case",
"xpath",
":",
"// Work around HLWK driver bug",
"return",
"By",
".",
"xpath",
... | Convert a Identification to a By used in WebDriver Drivers.
@return the correct By specification of the current Identification. | [
"Convert",
"a",
"Identification",
"to",
"a",
"By",
"used",
"in",
"WebDriver",
"Drivers",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/Identification.java#L89-L116 |
160,404 | crawljax/crawljax | core/src/main/java/com/crawljax/core/configuration/CrawlElement.java | CrawlElement.escapeApostrophes | protected String escapeApostrophes(String text) {
String resultString;
if (text.contains("'")) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("concat('");
stringBuilder.append(text.replace("'", "',\"'\",'"));
stringBuilder.append("')");
resultString = stringBuilder.toString();
} else {
resultString = "'" + text + "'";
}
return resultString;
} | java | protected String escapeApostrophes(String text) {
String resultString;
if (text.contains("'")) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("concat('");
stringBuilder.append(text.replace("'", "',\"'\",'"));
stringBuilder.append("')");
resultString = stringBuilder.toString();
} else {
resultString = "'" + text + "'";
}
return resultString;
} | [
"protected",
"String",
"escapeApostrophes",
"(",
"String",
"text",
")",
"{",
"String",
"resultString",
";",
"if",
"(",
"text",
".",
"contains",
"(",
"\"'\"",
")",
")",
"{",
"StringBuilder",
"stringBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"string... | Returns a string to resolve apostrophe issue in xpath
@param text
@return the apostrophe resolved xpath value string | [
"Returns",
"a",
"string",
"to",
"resolve",
"apostrophe",
"issue",
"in",
"xpath"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/configuration/CrawlElement.java#L226-L238 |
160,405 | crawljax/crawljax | core/src/main/java/com/crawljax/core/CrawlController.java | CrawlController.call | @Override
public CrawlSession call() {
setMaximumCrawlTimeIfNeeded();
plugins.runPreCrawlingPlugins(config);
CrawlTaskConsumer firstConsumer = consumerFactory.get();
StateVertex firstState = firstConsumer.crawlIndex();
crawlSessionProvider.setup(firstState);
plugins.runOnNewStatePlugins(firstConsumer.getContext(), firstState);
executeConsumers(firstConsumer);
return crawlSessionProvider.get();
} | java | @Override
public CrawlSession call() {
setMaximumCrawlTimeIfNeeded();
plugins.runPreCrawlingPlugins(config);
CrawlTaskConsumer firstConsumer = consumerFactory.get();
StateVertex firstState = firstConsumer.crawlIndex();
crawlSessionProvider.setup(firstState);
plugins.runOnNewStatePlugins(firstConsumer.getContext(), firstState);
executeConsumers(firstConsumer);
return crawlSessionProvider.get();
} | [
"@",
"Override",
"public",
"CrawlSession",
"call",
"(",
")",
"{",
"setMaximumCrawlTimeIfNeeded",
"(",
")",
";",
"plugins",
".",
"runPreCrawlingPlugins",
"(",
"config",
")",
";",
"CrawlTaskConsumer",
"firstConsumer",
"=",
"consumerFactory",
".",
"get",
"(",
")",
... | Run the configured crawl. This method blocks until the crawl is done.
@return the CrawlSession once the crawl is done. | [
"Run",
"the",
"configured",
"crawl",
".",
"This",
"method",
"blocks",
"until",
"the",
"crawl",
"is",
"done",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CrawlController.java#L64-L74 |
160,406 | crawljax/crawljax | core/src/main/java/com/crawljax/core/CandidateElementExtractor.java | CandidateElementExtractor.extract | public ImmutableList<CandidateElement> extract(StateVertex currentState)
throws CrawljaxException {
LinkedList<CandidateElement> results = new LinkedList<>();
if (!checkedElements.checkCrawlCondition(browser)) {
LOG.info("State {} did not satisfy the CrawlConditions.", currentState.getName());
return ImmutableList.of();
}
LOG.debug("Looking in state: {} for candidate elements", currentState.getName());
try {
Document dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());
extractElements(dom, results, "");
} catch (IOException e) {
LOG.error(e.getMessage(), e);
throw new CrawljaxException(e);
}
if (randomizeElementsOrder) {
Collections.shuffle(results);
}
currentState.setElementsFound(results);
LOG.debug("Found {} new candidate elements to analyze!", results.size());
return ImmutableList.copyOf(results);
} | java | public ImmutableList<CandidateElement> extract(StateVertex currentState)
throws CrawljaxException {
LinkedList<CandidateElement> results = new LinkedList<>();
if (!checkedElements.checkCrawlCondition(browser)) {
LOG.info("State {} did not satisfy the CrawlConditions.", currentState.getName());
return ImmutableList.of();
}
LOG.debug("Looking in state: {} for candidate elements", currentState.getName());
try {
Document dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());
extractElements(dom, results, "");
} catch (IOException e) {
LOG.error(e.getMessage(), e);
throw new CrawljaxException(e);
}
if (randomizeElementsOrder) {
Collections.shuffle(results);
}
currentState.setElementsFound(results);
LOG.debug("Found {} new candidate elements to analyze!", results.size());
return ImmutableList.copyOf(results);
} | [
"public",
"ImmutableList",
"<",
"CandidateElement",
">",
"extract",
"(",
"StateVertex",
"currentState",
")",
"throws",
"CrawljaxException",
"{",
"LinkedList",
"<",
"CandidateElement",
">",
"results",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"if",
"(",
"!",... | This method extracts candidate elements from the current DOM tree in the browser, based on
the crawl tags defined by the user.
@param currentState the state in which this extract method is requested.
@return a list of candidate elements that are not excluded.
@throws CrawljaxException if the method fails. | [
"This",
"method",
"extracts",
"candidate",
"elements",
"from",
"the",
"current",
"DOM",
"tree",
"in",
"the",
"browser",
"based",
"on",
"the",
"crawl",
"tags",
"defined",
"by",
"the",
"user",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CandidateElementExtractor.java#L110-L133 |
160,407 | crawljax/crawljax | core/src/main/java/com/crawljax/core/CandidateElementExtractor.java | CandidateElementExtractor.getNodeListForTagElement | private ImmutableList<Element> getNodeListForTagElement(Document dom,
CrawlElement crawlElement,
EventableConditionChecker eventableConditionChecker) {
Builder<Element> result = ImmutableList.builder();
if (crawlElement.getTagName() == null) {
return result.build();
}
EventableCondition eventableCondition =
eventableConditionChecker.getEventableCondition(crawlElement.getId());
// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent
// performance problems.
ImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);
NodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());
for (int k = 0; k < nodeList.getLength(); k++) {
Element element = (Element) nodeList.item(k);
boolean matchesXpath =
elementMatchesXpath(eventableConditionChecker, eventableCondition,
expressions, element);
LOG.debug("Element {} matches Xpath={}", DomUtils.getElementString(element),
matchesXpath);
/*
* TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return
* false and when needed to add it can return true. / check if element is a candidate
*/
String id = element.getNodeName() + ": " + DomUtils.getAllElementAttributes(element);
if (matchesXpath && !checkedElements.isChecked(id)
&& !isExcluded(dom, element, eventableConditionChecker)) {
addElement(element, result, crawlElement);
} else {
LOG.debug("Element {} was not added", element);
}
}
return result.build();
} | java | private ImmutableList<Element> getNodeListForTagElement(Document dom,
CrawlElement crawlElement,
EventableConditionChecker eventableConditionChecker) {
Builder<Element> result = ImmutableList.builder();
if (crawlElement.getTagName() == null) {
return result.build();
}
EventableCondition eventableCondition =
eventableConditionChecker.getEventableCondition(crawlElement.getId());
// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent
// performance problems.
ImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);
NodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());
for (int k = 0; k < nodeList.getLength(); k++) {
Element element = (Element) nodeList.item(k);
boolean matchesXpath =
elementMatchesXpath(eventableConditionChecker, eventableCondition,
expressions, element);
LOG.debug("Element {} matches Xpath={}", DomUtils.getElementString(element),
matchesXpath);
/*
* TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return
* false and when needed to add it can return true. / check if element is a candidate
*/
String id = element.getNodeName() + ": " + DomUtils.getAllElementAttributes(element);
if (matchesXpath && !checkedElements.isChecked(id)
&& !isExcluded(dom, element, eventableConditionChecker)) {
addElement(element, result, crawlElement);
} else {
LOG.debug("Element {} was not added", element);
}
}
return result.build();
} | [
"private",
"ImmutableList",
"<",
"Element",
">",
"getNodeListForTagElement",
"(",
"Document",
"dom",
",",
"CrawlElement",
"crawlElement",
",",
"EventableConditionChecker",
"eventableConditionChecker",
")",
"{",
"Builder",
"<",
"Element",
">",
"result",
"=",
"ImmutableLi... | Returns a list of Elements form the DOM tree, matching the tag element. | [
"Returns",
"a",
"list",
"of",
"Elements",
"form",
"the",
"DOM",
"tree",
"matching",
"the",
"tag",
"element",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CandidateElementExtractor.java#L226-L265 |
160,408 | crawljax/crawljax | core/src/main/java/com/crawljax/core/plugin/Plugins.java | Plugins.runOnInvariantViolationPlugins | public void runOnInvariantViolationPlugins(Invariant invariant,
CrawlerContext context) {
LOGGER.debug("Running OnInvariantViolationPlugins...");
counters.get(OnInvariantViolationPlugin.class).inc();
for (Plugin plugin : plugins.get(OnInvariantViolationPlugin.class)) {
if (plugin instanceof OnInvariantViolationPlugin) {
try {
LOGGER.debug("Calling plugin {}", plugin);
((OnInvariantViolationPlugin) plugin).onInvariantViolation(
invariant, context);
} catch (RuntimeException e) {
reportFailingPlugin(plugin, e);
}
}
}
} | java | public void runOnInvariantViolationPlugins(Invariant invariant,
CrawlerContext context) {
LOGGER.debug("Running OnInvariantViolationPlugins...");
counters.get(OnInvariantViolationPlugin.class).inc();
for (Plugin plugin : plugins.get(OnInvariantViolationPlugin.class)) {
if (plugin instanceof OnInvariantViolationPlugin) {
try {
LOGGER.debug("Calling plugin {}", plugin);
((OnInvariantViolationPlugin) plugin).onInvariantViolation(
invariant, context);
} catch (RuntimeException e) {
reportFailingPlugin(plugin, e);
}
}
}
} | [
"public",
"void",
"runOnInvariantViolationPlugins",
"(",
"Invariant",
"invariant",
",",
"CrawlerContext",
"context",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Running OnInvariantViolationPlugins...\"",
")",
";",
"counters",
".",
"get",
"(",
"OnInvariantViolationPlugin",
... | Run the OnInvariantViolation plugins when an Invariant is violated. Invariant are checked
when the state machine is updated that is when the dom is changed after a click on a
clickable. When a invariant fails this kind of plugins are executed. Warning the session is
not a clone, changing the session can cause strange behaviour of Crawljax.
@param invariant the failed invariants
@param context the current {@link CrawlerContext} for this crawler. | [
"Run",
"the",
"OnInvariantViolation",
"plugins",
"when",
"an",
"Invariant",
"is",
"violated",
".",
"Invariant",
"are",
"checked",
"when",
"the",
"state",
"machine",
"is",
"updated",
"that",
"is",
"when",
"the",
"dom",
"is",
"changed",
"after",
"a",
"click",
... | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/plugin/Plugins.java#L178-L193 |
160,409 | crawljax/crawljax | core/src/main/java/com/crawljax/core/plugin/Plugins.java | Plugins.runOnBrowserCreatedPlugins | public void runOnBrowserCreatedPlugins(EmbeddedBrowser newBrowser) {
LOGGER.debug("Running OnBrowserCreatedPlugins...");
counters.get(OnBrowserCreatedPlugin.class).inc();
for (Plugin plugin : plugins.get(OnBrowserCreatedPlugin.class)) {
if (plugin instanceof OnBrowserCreatedPlugin) {
LOGGER.debug("Calling plugin {}", plugin);
try {
((OnBrowserCreatedPlugin) plugin)
.onBrowserCreated(newBrowser);
} catch (RuntimeException e) {
reportFailingPlugin(plugin, e);
}
}
}
} | java | public void runOnBrowserCreatedPlugins(EmbeddedBrowser newBrowser) {
LOGGER.debug("Running OnBrowserCreatedPlugins...");
counters.get(OnBrowserCreatedPlugin.class).inc();
for (Plugin plugin : plugins.get(OnBrowserCreatedPlugin.class)) {
if (plugin instanceof OnBrowserCreatedPlugin) {
LOGGER.debug("Calling plugin {}", plugin);
try {
((OnBrowserCreatedPlugin) plugin)
.onBrowserCreated(newBrowser);
} catch (RuntimeException e) {
reportFailingPlugin(plugin, e);
}
}
}
} | [
"public",
"void",
"runOnBrowserCreatedPlugins",
"(",
"EmbeddedBrowser",
"newBrowser",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Running OnBrowserCreatedPlugins...\"",
")",
";",
"counters",
".",
"get",
"(",
"OnBrowserCreatedPlugin",
".",
"class",
")",
".",
"inc",
"("... | Load and run the OnBrowserCreatedPlugins, this call has been made from the browser pool when a
new browser has been created and ready to be used by the Crawler. The PreCrawling plugins are
executed before these plugins are executed except that the pre-crawling plugins are only
executed on the first created browser.
@param newBrowser the new created browser object | [
"Load",
"and",
"run",
"the",
"OnBrowserCreatedPlugins",
"this",
"call",
"has",
"been",
"made",
"from",
"the",
"browser",
"pool",
"when",
"a",
"new",
"browser",
"has",
"been",
"created",
"and",
"ready",
"to",
"be",
"used",
"by",
"the",
"Crawler",
".",
"The"... | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/plugin/Plugins.java#L323-L337 |
160,410 | crawljax/crawljax | core/src/main/java/com/crawljax/core/state/Element.java | Element.equalId | public boolean equalId(Element otherElement) {
if (getElementId() == null || otherElement.getElementId() == null) {
return false;
}
return getElementId().equalsIgnoreCase(otherElement.getElementId());
} | java | public boolean equalId(Element otherElement) {
if (getElementId() == null || otherElement.getElementId() == null) {
return false;
}
return getElementId().equalsIgnoreCase(otherElement.getElementId());
} | [
"public",
"boolean",
"equalId",
"(",
"Element",
"otherElement",
")",
"{",
"if",
"(",
"getElementId",
"(",
")",
"==",
"null",
"||",
"otherElement",
".",
"getElementId",
"(",
")",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"getElementId",... | Are both Id's the same?
@param otherElement the other element to compare
@return true if id == otherElement.id | [
"Are",
"both",
"Id",
"s",
"the",
"same?"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/Element.java#L67-L72 |
160,411 | crawljax/crawljax | core/src/main/java/com/crawljax/core/state/Element.java | Element.getElementId | public String getElementId() {
for (Entry<String, String> attribute : attributes.entrySet()) {
if (attribute.getKey().equalsIgnoreCase("id")) {
return attribute.getValue();
}
}
return null;
} | java | public String getElementId() {
for (Entry<String, String> attribute : attributes.entrySet()) {
if (attribute.getKey().equalsIgnoreCase("id")) {
return attribute.getValue();
}
}
return null;
} | [
"public",
"String",
"getElementId",
"(",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"String",
">",
"attribute",
":",
"attributes",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"attribute",
".",
"getKey",
"(",
")",
".",
"equalsIgnoreCase",
"(... | Search for the attribute "id" and return the value.
@return the id of this element or null when not found | [
"Search",
"for",
"the",
"attribute",
"id",
"and",
"return",
"the",
"value",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/Element.java#L89-L96 |
160,412 | crawljax/crawljax | core/src/main/java/com/crawljax/condition/eventablecondition/EventableConditionChecker.java | EventableConditionChecker.checkXpathStartsWithXpathEventableCondition | public boolean checkXpathStartsWithXpathEventableCondition(Document dom,
EventableCondition eventableCondition, String xpath) throws XPathExpressionException {
if (eventableCondition == null || Strings
.isNullOrEmpty(eventableCondition.getInXPath())) {
throw new CrawljaxException("Eventable has no XPath condition");
}
List<String> expressions =
XPathHelper.getXpathForXPathExpressions(dom, eventableCondition.getInXPath());
return checkXPathUnderXPaths(xpath, expressions);
} | java | public boolean checkXpathStartsWithXpathEventableCondition(Document dom,
EventableCondition eventableCondition, String xpath) throws XPathExpressionException {
if (eventableCondition == null || Strings
.isNullOrEmpty(eventableCondition.getInXPath())) {
throw new CrawljaxException("Eventable has no XPath condition");
}
List<String> expressions =
XPathHelper.getXpathForXPathExpressions(dom, eventableCondition.getInXPath());
return checkXPathUnderXPaths(xpath, expressions);
} | [
"public",
"boolean",
"checkXpathStartsWithXpathEventableCondition",
"(",
"Document",
"dom",
",",
"EventableCondition",
"eventableCondition",
",",
"String",
"xpath",
")",
"throws",
"XPathExpressionException",
"{",
"if",
"(",
"eventableCondition",
"==",
"null",
"||",
"Strin... | Checks whether an XPath expression starts with an XPath eventable condition.
@param dom The DOM String.
@param eventableCondition The eventable condition.
@param xpath The XPath.
@return boolean whether xpath starts with xpath location of eventable condition xpath
condition
@throws XPathExpressionException
@throws CrawljaxException when eventableCondition is null or its inXPath has not been set | [
"Checks",
"whether",
"an",
"XPath",
"expression",
"starts",
"with",
"an",
"XPath",
"eventable",
"condition",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/condition/eventablecondition/EventableConditionChecker.java#L66-L76 |
160,413 | crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTEDUtils.java | RTEDUtils.getRobustTreeEditDistance | public static double getRobustTreeEditDistance(String dom1, String dom2) {
LblTree domTree1 = null, domTree2 = null;
try {
domTree1 = getDomTree(dom1);
domTree2 = getDomTree(dom2);
} catch (IOException e) {
e.printStackTrace();
}
double DD = 0.0;
RTED_InfoTree_Opt rted;
double ted;
rted = new RTED_InfoTree_Opt(1, 1, 1);
// compute tree edit distance
rted.init(domTree1, domTree2);
int maxSize = Math.max(domTree1.getNodeCount(), domTree2.getNodeCount());
rted.computeOptimalStrategy();
ted = rted.nonNormalizedTreeDist();
ted /= (double) maxSize;
DD = ted;
return DD;
} | java | public static double getRobustTreeEditDistance(String dom1, String dom2) {
LblTree domTree1 = null, domTree2 = null;
try {
domTree1 = getDomTree(dom1);
domTree2 = getDomTree(dom2);
} catch (IOException e) {
e.printStackTrace();
}
double DD = 0.0;
RTED_InfoTree_Opt rted;
double ted;
rted = new RTED_InfoTree_Opt(1, 1, 1);
// compute tree edit distance
rted.init(domTree1, domTree2);
int maxSize = Math.max(domTree1.getNodeCount(), domTree2.getNodeCount());
rted.computeOptimalStrategy();
ted = rted.nonNormalizedTreeDist();
ted /= (double) maxSize;
DD = ted;
return DD;
} | [
"public",
"static",
"double",
"getRobustTreeEditDistance",
"(",
"String",
"dom1",
",",
"String",
"dom2",
")",
"{",
"LblTree",
"domTree1",
"=",
"null",
",",
"domTree2",
"=",
"null",
";",
"try",
"{",
"domTree1",
"=",
"getDomTree",
"(",
"dom1",
")",
";",
"dom... | Get a scalar value for the DOM diversity using the Robust Tree Edit Distance
@param dom1
@param dom2
@return | [
"Get",
"a",
"scalar",
"value",
"for",
"the",
"DOM",
"diversity",
"using",
"the",
"Robust",
"Tree",
"Edit",
"Distance"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTEDUtils.java#L20-L47 |
160,414 | crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTEDUtils.java | RTEDUtils.createTree | private static LblTree createTree(TreeWalker walker) {
Node parent = walker.getCurrentNode();
LblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1
for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {
node.add(createTree(walker));
}
walker.setCurrentNode(parent);
return node;
} | java | private static LblTree createTree(TreeWalker walker) {
Node parent = walker.getCurrentNode();
LblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1
for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {
node.add(createTree(walker));
}
walker.setCurrentNode(parent);
return node;
} | [
"private",
"static",
"LblTree",
"createTree",
"(",
"TreeWalker",
"walker",
")",
"{",
"Node",
"parent",
"=",
"walker",
".",
"getCurrentNode",
"(",
")",
";",
"LblTree",
"node",
"=",
"new",
"LblTree",
"(",
"parent",
".",
"getNodeName",
"(",
")",
",",
"-",
"... | Recursively construct a LblTree from DOM tree
@param walker tree walker for DOM tree traversal
@return tree represented by DOM tree | [
"Recursively",
"construct",
"a",
"LblTree",
"from",
"DOM",
"tree"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTEDUtils.java#L69-L77 |
160,415 | crawljax/crawljax | core/src/main/java/com/crawljax/core/configuration/CrawlActionsBuilder.java | CrawlActionsBuilder.dontClickChildrenOf | public ExcludeByParentBuilder dontClickChildrenOf(String tagName) {
checkNotRead();
Preconditions.checkNotNull(tagName);
ExcludeByParentBuilder exclude = new ExcludeByParentBuilder(
tagName.toUpperCase());
crawlParentsExcluded.add(exclude);
return exclude;
} | java | public ExcludeByParentBuilder dontClickChildrenOf(String tagName) {
checkNotRead();
Preconditions.checkNotNull(tagName);
ExcludeByParentBuilder exclude = new ExcludeByParentBuilder(
tagName.toUpperCase());
crawlParentsExcluded.add(exclude);
return exclude;
} | [
"public",
"ExcludeByParentBuilder",
"dontClickChildrenOf",
"(",
"String",
"tagName",
")",
"{",
"checkNotRead",
"(",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"tagName",
")",
";",
"ExcludeByParentBuilder",
"exclude",
"=",
"new",
"ExcludeByParentBuilder",
"("... | Click no children of the specified parent element.
@param tagName The tag name of which no children should be clicked.
@return The builder to append more options. | [
"Click",
"no",
"children",
"of",
"the",
"specified",
"parent",
"element",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/configuration/CrawlActionsBuilder.java#L147-L154 |
160,416 | crawljax/crawljax | core/src/main/java/com/crawljax/core/configuration/Form.java | Form.inputField | public FormInput inputField(InputType type, Identification identification) {
FormInput input = new FormInput(type, identification);
this.formInputs.add(input);
return input;
} | java | public FormInput inputField(InputType type, Identification identification) {
FormInput input = new FormInput(type, identification);
this.formInputs.add(input);
return input;
} | [
"public",
"FormInput",
"inputField",
"(",
"InputType",
"type",
",",
"Identification",
"identification",
")",
"{",
"FormInput",
"input",
"=",
"new",
"FormInput",
"(",
"type",
",",
"identification",
")",
";",
"this",
".",
"formInputs",
".",
"add",
"(",
"input",
... | Specifies an input field to assign a value to. Crawljax first tries to match the found HTML
input element's id and then the name attribute.
@param type
the type of input field
@param identification
the locator of the input field
@return an InputField | [
"Specifies",
"an",
"input",
"field",
"to",
"assign",
"a",
"value",
"to",
".",
"Crawljax",
"first",
"tries",
"to",
"match",
"the",
"found",
"HTML",
"input",
"element",
"s",
"id",
"and",
"then",
"the",
"name",
"attribute",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/configuration/Form.java#L55-L59 |
160,417 | crawljax/crawljax | cli/src/main/java/com/crawljax/cli/ParameterInterpeter.java | ParameterInterpeter.getOptions | private Options getOptions() {
Options options = new Options();
options.addOption("h", HELP, false, "print this message");
options.addOption(VERSION, false, "print the version information and exit");
options.addOption("b", BROWSER, true,
"browser type: " + availableBrowsers() + ". Default is Firefox");
options.addOption(BROWSER_REMOTE_URL, true,
"The remote url if you have configured a remote browser");
options.addOption("d", DEPTH, true, "crawl depth level. Default is 2");
options.addOption("s", MAXSTATES, true,
"max number of states to crawl. Default is 0 (unlimited)");
options.addOption("p", PARALLEL, true,
"Number of browsers to use for crawling. Default is 1");
options.addOption("o", OVERRIDE, false, "Override the output directory if non-empty");
options.addOption("a", CRAWL_HIDDEN_ANCHORS, false,
"Crawl anchors even if they are not visible in the browser.");
options.addOption("t", TIME_OUT, true,
"Specify the maximum crawl time in minutes");
options.addOption(CLICK, true,
"a comma separated list of HTML tags that should be clicked. Default is A and BUTTON");
options.addOption(WAIT_AFTER_EVENT, true,
"the time to wait after an event has been fired in milliseconds. Default is "
+ CrawlRules.DEFAULT_WAIT_AFTER_EVENT);
options.addOption(WAIT_AFTER_RELOAD, true,
"the time to wait after an URL has been loaded in milliseconds. Default is "
+ CrawlRules.DEFAULT_WAIT_AFTER_RELOAD);
options.addOption("v", VERBOSE, false, "Be extra verbose");
options.addOption(LOG_FILE, true, "Log to this file instead of the console");
return options;
} | java | private Options getOptions() {
Options options = new Options();
options.addOption("h", HELP, false, "print this message");
options.addOption(VERSION, false, "print the version information and exit");
options.addOption("b", BROWSER, true,
"browser type: " + availableBrowsers() + ". Default is Firefox");
options.addOption(BROWSER_REMOTE_URL, true,
"The remote url if you have configured a remote browser");
options.addOption("d", DEPTH, true, "crawl depth level. Default is 2");
options.addOption("s", MAXSTATES, true,
"max number of states to crawl. Default is 0 (unlimited)");
options.addOption("p", PARALLEL, true,
"Number of browsers to use for crawling. Default is 1");
options.addOption("o", OVERRIDE, false, "Override the output directory if non-empty");
options.addOption("a", CRAWL_HIDDEN_ANCHORS, false,
"Crawl anchors even if they are not visible in the browser.");
options.addOption("t", TIME_OUT, true,
"Specify the maximum crawl time in minutes");
options.addOption(CLICK, true,
"a comma separated list of HTML tags that should be clicked. Default is A and BUTTON");
options.addOption(WAIT_AFTER_EVENT, true,
"the time to wait after an event has been fired in milliseconds. Default is "
+ CrawlRules.DEFAULT_WAIT_AFTER_EVENT);
options.addOption(WAIT_AFTER_RELOAD, true,
"the time to wait after an URL has been loaded in milliseconds. Default is "
+ CrawlRules.DEFAULT_WAIT_AFTER_RELOAD);
options.addOption("v", VERBOSE, false, "Be extra verbose");
options.addOption(LOG_FILE, true, "Log to this file instead of the console");
return options;
} | [
"private",
"Options",
"getOptions",
"(",
")",
"{",
"Options",
"options",
"=",
"new",
"Options",
"(",
")",
";",
"options",
".",
"addOption",
"(",
"\"h\"",
",",
"HELP",
",",
"false",
",",
"\"print this message\"",
")",
";",
"options",
".",
"addOption",
"(",
... | Create the CML Options.
@return Options expected from command-line. | [
"Create",
"the",
"CML",
"Options",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/cli/src/main/java/com/crawljax/cli/ParameterInterpeter.java#L61-L102 |
160,418 | crawljax/crawljax | core/src/main/java/com/crawljax/util/FSUtils.java | FSUtils.directoryCheck | public static void directoryCheck(String dir) throws IOException {
final File file = new File(dir);
if (!file.exists()) {
FileUtils.forceMkdir(file);
}
} | java | public static void directoryCheck(String dir) throws IOException {
final File file = new File(dir);
if (!file.exists()) {
FileUtils.forceMkdir(file);
}
} | [
"public",
"static",
"void",
"directoryCheck",
"(",
"String",
"dir",
")",
"throws",
"IOException",
"{",
"final",
"File",
"file",
"=",
"new",
"File",
"(",
"dir",
")",
";",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"FileUtils",
".",
"fo... | Checks the existence of the directory. If it does not exist, the method creates it.
@param dir the directory to check.
@throws IOException if fails. | [
"Checks",
"the",
"existence",
"of",
"the",
"directory",
".",
"If",
"it",
"does",
"not",
"exist",
"the",
"method",
"creates",
"it",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/FSUtils.java#L16-L22 |
160,419 | crawljax/crawljax | core/src/main/java/com/crawljax/util/FSUtils.java | FSUtils.checkFolderForFile | public static void checkFolderForFile(String fileName) throws IOException {
if (fileName.lastIndexOf(File.separator) > 0) {
String folder = fileName.substring(0, fileName.lastIndexOf(File.separator));
directoryCheck(folder);
}
} | java | public static void checkFolderForFile(String fileName) throws IOException {
if (fileName.lastIndexOf(File.separator) > 0) {
String folder = fileName.substring(0, fileName.lastIndexOf(File.separator));
directoryCheck(folder);
}
} | [
"public",
"static",
"void",
"checkFolderForFile",
"(",
"String",
"fileName",
")",
"throws",
"IOException",
"{",
"if",
"(",
"fileName",
".",
"lastIndexOf",
"(",
"File",
".",
"separator",
")",
">",
"0",
")",
"{",
"String",
"folder",
"=",
"fileName",
".",
"su... | Checks whether the folder exists for fileName, and creates it if necessary.
@param fileName folder name.
@throws IOException an IO exception. | [
"Checks",
"whether",
"the",
"folder",
"exists",
"for",
"fileName",
"and",
"creates",
"it",
"if",
"necessary",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/FSUtils.java#L30-L36 |
160,420 | crawljax/crawljax | core/src/main/java/com/crawljax/core/CandidateElementManager.java | CandidateElementManager.markChecked | @GuardedBy("elementsLock")
@Override
public boolean markChecked(CandidateElement element) {
String generalString = element.getGeneralString();
String uniqueString = element.getUniqueString();
synchronized (elementsLock) {
if (elements.contains(uniqueString)) {
return false;
} else {
elements.add(generalString);
elements.add(uniqueString);
return true;
}
}
} | java | @GuardedBy("elementsLock")
@Override
public boolean markChecked(CandidateElement element) {
String generalString = element.getGeneralString();
String uniqueString = element.getUniqueString();
synchronized (elementsLock) {
if (elements.contains(uniqueString)) {
return false;
} else {
elements.add(generalString);
elements.add(uniqueString);
return true;
}
}
} | [
"@",
"GuardedBy",
"(",
"\"elementsLock\"",
")",
"@",
"Override",
"public",
"boolean",
"markChecked",
"(",
"CandidateElement",
"element",
")",
"{",
"String",
"generalString",
"=",
"element",
".",
"getGeneralString",
"(",
")",
";",
"String",
"uniqueString",
"=",
"... | Mark a given element as checked to prevent duplicate work. A elements is only added when it
is not already in the set of checked elements.
@param element the element that is checked
@return true if !contains(element.uniqueString) | [
"Mark",
"a",
"given",
"element",
"as",
"checked",
"to",
"prevent",
"duplicate",
"work",
".",
"A",
"elements",
"is",
"only",
"added",
"when",
"it",
"is",
"not",
"already",
"in",
"the",
"set",
"of",
"checked",
"elements",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CandidateElementManager.java#L90-L104 |
160,421 | crawljax/crawljax | core/src/main/java/com/crawljax/core/CrawljaxRunner.java | CrawljaxRunner.readFormDataFromFile | private void readFormDataFromFile() {
List<FormInput> formInputList =
FormInputValueHelper.deserializeFormInputs(config.getSiteDir());
if (formInputList != null) {
InputSpecification inputSpecs = config.getCrawlRules().getInputSpecification();
for (FormInput input : formInputList) {
inputSpecs.inputField(input);
}
}
} | java | private void readFormDataFromFile() {
List<FormInput> formInputList =
FormInputValueHelper.deserializeFormInputs(config.getSiteDir());
if (formInputList != null) {
InputSpecification inputSpecs = config.getCrawlRules().getInputSpecification();
for (FormInput input : formInputList) {
inputSpecs.inputField(input);
}
}
} | [
"private",
"void",
"readFormDataFromFile",
"(",
")",
"{",
"List",
"<",
"FormInput",
">",
"formInputList",
"=",
"FormInputValueHelper",
".",
"deserializeFormInputs",
"(",
"config",
".",
"getSiteDir",
"(",
")",
")",
";",
"if",
"(",
"formInputList",
"!=",
"null",
... | Reads input data from a JSON file in the output directory. | [
"Reads",
"input",
"data",
"from",
"a",
"JSON",
"file",
"in",
"the",
"output",
"directory",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CrawljaxRunner.java#L37-L48 |
160,422 | crawljax/crawljax | core/src/main/java/com/crawljax/core/CrawljaxRunner.java | CrawljaxRunner.call | @Override
public CrawlSession call() {
Injector injector = Guice.createInjector(new CoreModule(config));
controller = injector.getInstance(CrawlController.class);
CrawlSession session = controller.call();
reason = controller.getReason();
return session;
} | java | @Override
public CrawlSession call() {
Injector injector = Guice.createInjector(new CoreModule(config));
controller = injector.getInstance(CrawlController.class);
CrawlSession session = controller.call();
reason = controller.getReason();
return session;
} | [
"@",
"Override",
"public",
"CrawlSession",
"call",
"(",
")",
"{",
"Injector",
"injector",
"=",
"Guice",
".",
"createInjector",
"(",
"new",
"CoreModule",
"(",
"config",
")",
")",
";",
"controller",
"=",
"injector",
".",
"getInstance",
"(",
"CrawlController",
... | Runs Crawljax with the given configuration.
@return The {@link CrawlSession} once the Crawl is done. | [
"Runs",
"Crawljax",
"with",
"the",
"given",
"configuration",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CrawljaxRunner.java#L55-L62 |
160,423 | crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/visual/imagehashes/DHash.java | DHash.distance | public static Integer distance(String h1, String h2) {
HammingDistance distance = new HammingDistance();
return distance.apply(h1, h2);
} | java | public static Integer distance(String h1, String h2) {
HammingDistance distance = new HammingDistance();
return distance.apply(h1, h2);
} | [
"public",
"static",
"Integer",
"distance",
"(",
"String",
"h1",
",",
"String",
"h2",
")",
"{",
"HammingDistance",
"distance",
"=",
"new",
"HammingDistance",
"(",
")",
";",
"return",
"distance",
".",
"apply",
"(",
"h1",
",",
"h2",
")",
";",
"}"
] | Calculate the Hamming distance between two hashes
@param h1
@param h2
@return | [
"Calculate",
"the",
"Hamming",
"distance",
"between",
"two",
"hashes"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/visual/imagehashes/DHash.java#L122-L125 |
160,424 | crawljax/crawljax | core/src/main/java/com/crawljax/forms/FormInputValueHelper.java | FormInputValueHelper.getInstance | public static synchronized FormInputValueHelper getInstance(
InputSpecification inputSpecification, FormFillMode formFillMode) {
if (instance == null)
instance = new FormInputValueHelper(inputSpecification,
formFillMode);
return instance;
} | java | public static synchronized FormInputValueHelper getInstance(
InputSpecification inputSpecification, FormFillMode formFillMode) {
if (instance == null)
instance = new FormInputValueHelper(inputSpecification,
formFillMode);
return instance;
} | [
"public",
"static",
"synchronized",
"FormInputValueHelper",
"getInstance",
"(",
"InputSpecification",
"inputSpecification",
",",
"FormFillMode",
"formFillMode",
")",
"{",
"if",
"(",
"instance",
"==",
"null",
")",
"instance",
"=",
"new",
"FormInputValueHelper",
"(",
"i... | Creates or returns the instance of the helper class.
@param inputSpecification the input specification.
@param formFillMode if random data should be used on the input fields.
@return The singleton instance. | [
"Creates",
"or",
"returns",
"the",
"instance",
"of",
"the",
"helper",
"class",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/forms/FormInputValueHelper.java#L59-L65 |
160,425 | crawljax/crawljax | core/src/main/java/com/crawljax/forms/FormInputValueHelper.java | FormInputValueHelper.formInputMatchingNode | private FormInput formInputMatchingNode(Node element) {
NamedNodeMap attributes = element.getAttributes();
Identification id;
if (attributes.getNamedItem("id") != null
&& formFillMode != FormFillMode.XPATH_TRAINING) {
id = new Identification(Identification.How.id,
attributes.getNamedItem("id").getNodeValue());
FormInput input = this.formInputs.get(id);
if (input != null) {
return input;
}
}
if (attributes.getNamedItem("name") != null
&& formFillMode != FormFillMode.XPATH_TRAINING) {
id = new Identification(Identification.How.name,
attributes.getNamedItem("name").getNodeValue());
FormInput input = this.formInputs.get(id);
if (input != null) {
return input;
}
}
String xpathExpr = XPathHelper.getXPathExpression(element);
if (xpathExpr != null && !xpathExpr.equals("")) {
id = new Identification(Identification.How.xpath, xpathExpr);
FormInput input = this.formInputs.get(id);
if (input != null) {
return input;
}
}
return null;
} | java | private FormInput formInputMatchingNode(Node element) {
NamedNodeMap attributes = element.getAttributes();
Identification id;
if (attributes.getNamedItem("id") != null
&& formFillMode != FormFillMode.XPATH_TRAINING) {
id = new Identification(Identification.How.id,
attributes.getNamedItem("id").getNodeValue());
FormInput input = this.formInputs.get(id);
if (input != null) {
return input;
}
}
if (attributes.getNamedItem("name") != null
&& formFillMode != FormFillMode.XPATH_TRAINING) {
id = new Identification(Identification.How.name,
attributes.getNamedItem("name").getNodeValue());
FormInput input = this.formInputs.get(id);
if (input != null) {
return input;
}
}
String xpathExpr = XPathHelper.getXPathExpression(element);
if (xpathExpr != null && !xpathExpr.equals("")) {
id = new Identification(Identification.How.xpath, xpathExpr);
FormInput input = this.formInputs.get(id);
if (input != null) {
return input;
}
}
return null;
} | [
"private",
"FormInput",
"formInputMatchingNode",
"(",
"Node",
"element",
")",
"{",
"NamedNodeMap",
"attributes",
"=",
"element",
".",
"getAttributes",
"(",
")",
";",
"Identification",
"id",
";",
"if",
"(",
"attributes",
".",
"getNamedItem",
"(",
"\"id\"",
")",
... | return the list of FormInputs that match this element
@param element
@return | [
"return",
"the",
"list",
"of",
"FormInputs",
"that",
"match",
"this",
"element"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/forms/FormInputValueHelper.java#L300-L334 |
160,426 | crawljax/crawljax | core/src/main/java/com/crawljax/core/Crawler.java | Crawler.reset | public void reset() {
CrawlSession session = context.getSession();
if (crawlpath != null) {
session.addCrawlPath(crawlpath);
}
List<StateVertex> onURLSetTemp = new ArrayList<>();
if (stateMachine != null)
onURLSetTemp = stateMachine.getOnURLSet();
stateMachine = new StateMachine(graphProvider.get(), crawlRules.getInvariants(), plugins,
stateComparator, onURLSetTemp);
context.setStateMachine(stateMachine);
crawlpath = new CrawlPath();
context.setCrawlPath(crawlpath);
browser.handlePopups();
browser.goToUrl(url);
// Checks the landing page for URL and sets the current page accordingly
checkOnURLState();
plugins.runOnUrlLoadPlugins(context);
crawlDepth.set(0);
} | java | public void reset() {
CrawlSession session = context.getSession();
if (crawlpath != null) {
session.addCrawlPath(crawlpath);
}
List<StateVertex> onURLSetTemp = new ArrayList<>();
if (stateMachine != null)
onURLSetTemp = stateMachine.getOnURLSet();
stateMachine = new StateMachine(graphProvider.get(), crawlRules.getInvariants(), plugins,
stateComparator, onURLSetTemp);
context.setStateMachine(stateMachine);
crawlpath = new CrawlPath();
context.setCrawlPath(crawlpath);
browser.handlePopups();
browser.goToUrl(url);
// Checks the landing page for URL and sets the current page accordingly
checkOnURLState();
plugins.runOnUrlLoadPlugins(context);
crawlDepth.set(0);
} | [
"public",
"void",
"reset",
"(",
")",
"{",
"CrawlSession",
"session",
"=",
"context",
".",
"getSession",
"(",
")",
";",
"if",
"(",
"crawlpath",
"!=",
"null",
")",
"{",
"session",
".",
"addCrawlPath",
"(",
"crawlpath",
")",
";",
"}",
"List",
"<",
"StateV... | Reset the crawler to its initial state. | [
"Reset",
"the",
"crawler",
"to",
"its",
"initial",
"state",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/Crawler.java#L110-L129 |
160,427 | crawljax/crawljax | core/src/main/java/com/crawljax/core/Crawler.java | Crawler.fireEvent | private boolean fireEvent(Eventable eventable) {
Eventable eventToFire = eventable;
if (eventable.getIdentification().getHow().toString().equals("xpath")
&& eventable.getRelatedFrame().equals("")) {
eventToFire = resolveByXpath(eventable, eventToFire);
}
boolean isFired = false;
try {
isFired = browser.fireEventAndWait(eventToFire);
} catch (ElementNotVisibleException | NoSuchElementException e) {
if (crawlRules.isCrawlHiddenAnchors() && eventToFire.getElement() != null
&& "A".equals(eventToFire.getElement().getTag())) {
isFired = visitAnchorHrefIfPossible(eventToFire);
} else {
LOG.debug("Ignoring invisible element {}", eventToFire.getElement());
}
} catch (InterruptedException e) {
LOG.debug("Interrupted during fire event");
interruptThread();
return false;
}
LOG.debug("Event fired={} for eventable {}", isFired, eventable);
if (isFired) {
// Let the controller execute its specified wait operation on the browser thread safe.
waitConditionChecker.wait(browser);
browser.closeOtherWindows();
return true;
} else {
/*
* Execute the OnFireEventFailedPlugins with the current crawlPath with the crawlPath
* removed 1 state to represent the path TO here.
*/
plugins.runOnFireEventFailedPlugins(context, eventable,
crawlpath.immutableCopyWithoutLast());
return false; // no event fired
}
} | java | private boolean fireEvent(Eventable eventable) {
Eventable eventToFire = eventable;
if (eventable.getIdentification().getHow().toString().equals("xpath")
&& eventable.getRelatedFrame().equals("")) {
eventToFire = resolveByXpath(eventable, eventToFire);
}
boolean isFired = false;
try {
isFired = browser.fireEventAndWait(eventToFire);
} catch (ElementNotVisibleException | NoSuchElementException e) {
if (crawlRules.isCrawlHiddenAnchors() && eventToFire.getElement() != null
&& "A".equals(eventToFire.getElement().getTag())) {
isFired = visitAnchorHrefIfPossible(eventToFire);
} else {
LOG.debug("Ignoring invisible element {}", eventToFire.getElement());
}
} catch (InterruptedException e) {
LOG.debug("Interrupted during fire event");
interruptThread();
return false;
}
LOG.debug("Event fired={} for eventable {}", isFired, eventable);
if (isFired) {
// Let the controller execute its specified wait operation on the browser thread safe.
waitConditionChecker.wait(browser);
browser.closeOtherWindows();
return true;
} else {
/*
* Execute the OnFireEventFailedPlugins with the current crawlPath with the crawlPath
* removed 1 state to represent the path TO here.
*/
plugins.runOnFireEventFailedPlugins(context, eventable,
crawlpath.immutableCopyWithoutLast());
return false; // no event fired
}
} | [
"private",
"boolean",
"fireEvent",
"(",
"Eventable",
"eventable",
")",
"{",
"Eventable",
"eventToFire",
"=",
"eventable",
";",
"if",
"(",
"eventable",
".",
"getIdentification",
"(",
")",
".",
"getHow",
"(",
")",
".",
"toString",
"(",
")",
".",
"equals",
"(... | Try to fire a given event on the Browser.
@param eventable the eventable to fire
@return true iff the event is fired | [
"Try",
"to",
"fire",
"a",
"given",
"event",
"on",
"the",
"Browser",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/Crawler.java#L352-L390 |
160,428 | crawljax/crawljax | core/src/main/java/com/crawljax/core/Crawler.java | Crawler.crawlIndex | public StateVertex crawlIndex() {
LOG.debug("Setting up vertex of the index page");
if (basicAuthUrl != null) {
browser.goToUrl(basicAuthUrl);
}
browser.goToUrl(url);
// Run url first load plugin to clear the application state
plugins.runOnUrlFirstLoadPlugins(context);
plugins.runOnUrlLoadPlugins(context);
StateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(),
stateComparator.getStrippedDom(browser), browser);
Preconditions.checkArgument(index.getId() == StateVertex.INDEX_ID,
"It seems some the index state is crawled more than once.");
LOG.debug("Parsing the index for candidate elements");
ImmutableList<CandidateElement> extract = candidateExtractor.extract(index);
plugins.runPreStateCrawlingPlugins(context, extract, index);
candidateActionCache.addActions(extract, index);
return index;
} | java | public StateVertex crawlIndex() {
LOG.debug("Setting up vertex of the index page");
if (basicAuthUrl != null) {
browser.goToUrl(basicAuthUrl);
}
browser.goToUrl(url);
// Run url first load plugin to clear the application state
plugins.runOnUrlFirstLoadPlugins(context);
plugins.runOnUrlLoadPlugins(context);
StateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(),
stateComparator.getStrippedDom(browser), browser);
Preconditions.checkArgument(index.getId() == StateVertex.INDEX_ID,
"It seems some the index state is crawled more than once.");
LOG.debug("Parsing the index for candidate elements");
ImmutableList<CandidateElement> extract = candidateExtractor.extract(index);
plugins.runPreStateCrawlingPlugins(context, extract, index);
candidateActionCache.addActions(extract, index);
return index;
} | [
"public",
"StateVertex",
"crawlIndex",
"(",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Setting up vertex of the index page\"",
")",
";",
"if",
"(",
"basicAuthUrl",
"!=",
"null",
")",
"{",
"browser",
".",
"goToUrl",
"(",
"basicAuthUrl",
")",
";",
"}",
"browser",
... | This method calls the index state. It should be called once per crawl in order to setup the
crawl.
@return The initial state. | [
"This",
"method",
"calls",
"the",
"index",
"state",
".",
"It",
"should",
"be",
"called",
"once",
"per",
"crawl",
"in",
"order",
"to",
"setup",
"the",
"crawl",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/Crawler.java#L620-L647 |
160,429 | crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTED_InfoTree_Opt.java | RTED_InfoTree_Opt.nonNormalizedTreeDist | public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {
init(t1, t2);
STR = new int[size1][size2];
computeOptimalStrategy();
return computeDistUsingStrArray(it1, it2);
} | java | public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {
init(t1, t2);
STR = new int[size1][size2];
computeOptimalStrategy();
return computeDistUsingStrArray(it1, it2);
} | [
"public",
"double",
"nonNormalizedTreeDist",
"(",
"LblTree",
"t1",
",",
"LblTree",
"t2",
")",
"{",
"init",
"(",
"t1",
",",
"t2",
")",
";",
"STR",
"=",
"new",
"int",
"[",
"size1",
"]",
"[",
"size2",
"]",
";",
"computeOptimalStrategy",
"(",
")",
";",
"... | Computes the tree edit distance between trees t1 and t2.
@param t1
@param t2
@return tree edit distance between trees t1 and t2 | [
"Computes",
"the",
"tree",
"edit",
"distance",
"between",
"trees",
"t1",
"and",
"t2",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTED_InfoTree_Opt.java#L100-L105 |
160,430 | crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTED_InfoTree_Opt.java | RTED_InfoTree_Opt.init | public void init(LblTree t1, LblTree t2) {
LabelDictionary ld = new LabelDictionary();
it1 = new InfoTree(t1, ld);
it2 = new InfoTree(t2, ld);
size1 = it1.getSize();
size2 = it2.getSize();
IJ = new int[Math.max(size1, size2)][Math.max(size1, size2)];
delta = new double[size1][size2];
deltaBit = new byte[size1][size2];
costV = new long[3][size1][size2];
costW = new long[3][size2];
// Calculate delta between every leaf in G (empty tree) and all the nodes in F.
// Calculate it both sides: leafs of F and nodes of G & leafs of G and nodes of
// F.
int[] labels1 = it1.getInfoArray(POST2_LABEL);
int[] labels2 = it2.getInfoArray(POST2_LABEL);
int[] sizes1 = it1.getInfoArray(POST2_SIZE);
int[] sizes2 = it2.getInfoArray(POST2_SIZE);
for (int x = 0; x < sizes1.length; x++) { // for all nodes of initially left tree
for (int y = 0; y < sizes2.length; y++) { // for all nodes of initially right tree
// This is an attempt for distances of single-node subtree and anything alse
// The differences between pairs of labels are stored
if (labels1[x] == labels2[y]) {
deltaBit[x][y] = 0;
} else {
deltaBit[x][y] =
1; // if this set, the labels differ, cost of relabeling is set
// to costMatch
}
if (sizes1[x] == 1 && sizes2[y] == 1) { // both nodes are leafs
delta[x][y] = 0;
} else {
if (sizes1[x] == 1) {
delta[x][y] = sizes2[y] - 1;
}
if (sizes2[y] == 1) {
delta[x][y] = sizes1[x] - 1;
}
}
}
}
} | java | public void init(LblTree t1, LblTree t2) {
LabelDictionary ld = new LabelDictionary();
it1 = new InfoTree(t1, ld);
it2 = new InfoTree(t2, ld);
size1 = it1.getSize();
size2 = it2.getSize();
IJ = new int[Math.max(size1, size2)][Math.max(size1, size2)];
delta = new double[size1][size2];
deltaBit = new byte[size1][size2];
costV = new long[3][size1][size2];
costW = new long[3][size2];
// Calculate delta between every leaf in G (empty tree) and all the nodes in F.
// Calculate it both sides: leafs of F and nodes of G & leafs of G and nodes of
// F.
int[] labels1 = it1.getInfoArray(POST2_LABEL);
int[] labels2 = it2.getInfoArray(POST2_LABEL);
int[] sizes1 = it1.getInfoArray(POST2_SIZE);
int[] sizes2 = it2.getInfoArray(POST2_SIZE);
for (int x = 0; x < sizes1.length; x++) { // for all nodes of initially left tree
for (int y = 0; y < sizes2.length; y++) { // for all nodes of initially right tree
// This is an attempt for distances of single-node subtree and anything alse
// The differences between pairs of labels are stored
if (labels1[x] == labels2[y]) {
deltaBit[x][y] = 0;
} else {
deltaBit[x][y] =
1; // if this set, the labels differ, cost of relabeling is set
// to costMatch
}
if (sizes1[x] == 1 && sizes2[y] == 1) { // both nodes are leafs
delta[x][y] = 0;
} else {
if (sizes1[x] == 1) {
delta[x][y] = sizes2[y] - 1;
}
if (sizes2[y] == 1) {
delta[x][y] = sizes1[x] - 1;
}
}
}
}
} | [
"public",
"void",
"init",
"(",
"LblTree",
"t1",
",",
"LblTree",
"t2",
")",
"{",
"LabelDictionary",
"ld",
"=",
"new",
"LabelDictionary",
"(",
")",
";",
"it1",
"=",
"new",
"InfoTree",
"(",
"t1",
",",
"ld",
")",
";",
"it2",
"=",
"new",
"InfoTree",
"(",
... | Initialization method.
@param t1
@param t2 | [
"Initialization",
"method",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTED_InfoTree_Opt.java#L123-L167 |
160,431 | crawljax/crawljax | core/src/main/java/com/crawljax/core/state/StateMachine.java | StateMachine.changeState | public boolean changeState(StateVertex nextState) {
if (nextState == null) {
LOGGER.info("nextState given is null");
return false;
}
LOGGER.debug("Trying to change to state: '{}' from: '{}'", nextState.getName(),
currentState.getName());
if (stateFlowGraph.canGoTo(currentState, nextState)) {
LOGGER.debug("Changed to state: '{}' from: '{}'", nextState.getName(),
currentState.getName());
setCurrentState(nextState);
return true;
} else {
LOGGER.info("Cannot go to state: '{}' from: '{}'", nextState.getName(),
currentState.getName());
return false;
}
} | java | public boolean changeState(StateVertex nextState) {
if (nextState == null) {
LOGGER.info("nextState given is null");
return false;
}
LOGGER.debug("Trying to change to state: '{}' from: '{}'", nextState.getName(),
currentState.getName());
if (stateFlowGraph.canGoTo(currentState, nextState)) {
LOGGER.debug("Changed to state: '{}' from: '{}'", nextState.getName(),
currentState.getName());
setCurrentState(nextState);
return true;
} else {
LOGGER.info("Cannot go to state: '{}' from: '{}'", nextState.getName(),
currentState.getName());
return false;
}
} | [
"public",
"boolean",
"changeState",
"(",
"StateVertex",
"nextState",
")",
"{",
"if",
"(",
"nextState",
"==",
"null",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"nextState given is null\"",
")",
";",
"return",
"false",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\... | Change the currentState to the nextState if possible. The next state should already be
present in the graph.
@param nextState the next state.
@return true if currentState is successfully changed. | [
"Change",
"the",
"currentState",
"to",
"the",
"nextState",
"if",
"possible",
".",
"The",
"next",
"state",
"should",
"already",
"be",
"present",
"in",
"the",
"graph",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/StateMachine.java#L67-L88 |
160,432 | crawljax/crawljax | core/src/main/java/com/crawljax/core/state/StateMachine.java | StateMachine.addStateToCurrentState | private StateVertex addStateToCurrentState(StateVertex newState, Eventable eventable) {
LOGGER.debug("addStateToCurrentState currentState: {} newState {}",
currentState.getName(), newState.getName());
// Add the state to the stateFlowGraph. Store the result
StateVertex cloneState = stateFlowGraph.putIfAbsent(newState);
// Is there a clone detected?
if (cloneState != null) {
LOGGER.info("CLONE State detected: {} and {} are the same.", newState.getName(),
cloneState.getName());
LOGGER.debug("CLONE CURRENT STATE: {}", currentState.getName());
LOGGER.debug("CLONE STATE: {}", cloneState.getName());
LOGGER.debug("CLONE CLICKABLE: {}", eventable);
boolean added = stateFlowGraph.addEdge(currentState, cloneState, eventable);
if (!added) {
LOGGER.debug("Clone edge !! Need to fix the crawlPath??");
}
} else {
stateFlowGraph.addEdge(currentState, newState, eventable);
LOGGER.info("State {} added to the StateMachine.", newState.getName());
}
return cloneState;
} | java | private StateVertex addStateToCurrentState(StateVertex newState, Eventable eventable) {
LOGGER.debug("addStateToCurrentState currentState: {} newState {}",
currentState.getName(), newState.getName());
// Add the state to the stateFlowGraph. Store the result
StateVertex cloneState = stateFlowGraph.putIfAbsent(newState);
// Is there a clone detected?
if (cloneState != null) {
LOGGER.info("CLONE State detected: {} and {} are the same.", newState.getName(),
cloneState.getName());
LOGGER.debug("CLONE CURRENT STATE: {}", currentState.getName());
LOGGER.debug("CLONE STATE: {}", cloneState.getName());
LOGGER.debug("CLONE CLICKABLE: {}", eventable);
boolean added = stateFlowGraph.addEdge(currentState, cloneState, eventable);
if (!added) {
LOGGER.debug("Clone edge !! Need to fix the crawlPath??");
}
} else {
stateFlowGraph.addEdge(currentState, newState, eventable);
LOGGER.info("State {} added to the StateMachine.", newState.getName());
}
return cloneState;
} | [
"private",
"StateVertex",
"addStateToCurrentState",
"(",
"StateVertex",
"newState",
",",
"Eventable",
"eventable",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"addStateToCurrentState currentState: {} newState {}\"",
",",
"currentState",
".",
"getName",
"(",
")",
",",
"newS... | Adds the newState and the edge between the currentState and the newState on the SFG.
@param newState the new state.
@param eventable the clickable causing the new state.
@return the clone state iff newState is a clone, else returns null | [
"Adds",
"the",
"newState",
"and",
"the",
"edge",
"between",
"the",
"currentState",
"and",
"the",
"newState",
"on",
"the",
"SFG",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/StateMachine.java#L97-L121 |
160,433 | crawljax/crawljax | core/src/main/java/com/crawljax/core/state/StateMachine.java | StateMachine.switchToStateAndCheckIfClone | public boolean switchToStateAndCheckIfClone(final Eventable event, StateVertex newState,
CrawlerContext context) {
StateVertex cloneState = this.addStateToCurrentState(newState, event);
runOnInvariantViolationPlugins(context);
if (cloneState == null) {
changeState(newState);
plugins.runOnNewStatePlugins(context, newState);
return true;
} else {
changeState(cloneState);
return false;
}
} | java | public boolean switchToStateAndCheckIfClone(final Eventable event, StateVertex newState,
CrawlerContext context) {
StateVertex cloneState = this.addStateToCurrentState(newState, event);
runOnInvariantViolationPlugins(context);
if (cloneState == null) {
changeState(newState);
plugins.runOnNewStatePlugins(context, newState);
return true;
} else {
changeState(cloneState);
return false;
}
} | [
"public",
"boolean",
"switchToStateAndCheckIfClone",
"(",
"final",
"Eventable",
"event",
",",
"StateVertex",
"newState",
",",
"CrawlerContext",
"context",
")",
"{",
"StateVertex",
"cloneState",
"=",
"this",
".",
"addStateToCurrentState",
"(",
"newState",
",",
"event",... | Adds an edge between the current and new state.
@return true if the new state is not found in the state machine. | [
"Adds",
"an",
"edge",
"between",
"the",
"current",
"and",
"new",
"state",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/StateMachine.java#L144-L158 |
160,434 | crawljax/crawljax | cli/src/main/java/com/crawljax/cli/LogUtil.java | LogUtil.logToFile | @SuppressWarnings("unchecked")
static void logToFile(String filename) {
Logger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
FileAppender<ILoggingEvent> fileappender = new FileAppender<>();
fileappender.setContext(rootLogger.getLoggerContext());
fileappender.setFile(filename);
fileappender.setName("FILE");
ConsoleAppender<?> console = (ConsoleAppender<?>) rootLogger.getAppender("STDOUT");
fileappender.setEncoder((Encoder<ILoggingEvent>) console.getEncoder());
fileappender.start();
rootLogger.addAppender(fileappender);
console.stop();
} | java | @SuppressWarnings("unchecked")
static void logToFile(String filename) {
Logger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
FileAppender<ILoggingEvent> fileappender = new FileAppender<>();
fileappender.setContext(rootLogger.getLoggerContext());
fileappender.setFile(filename);
fileappender.setName("FILE");
ConsoleAppender<?> console = (ConsoleAppender<?>) rootLogger.getAppender("STDOUT");
fileappender.setEncoder((Encoder<ILoggingEvent>) console.getEncoder());
fileappender.start();
rootLogger.addAppender(fileappender);
console.stop();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"static",
"void",
"logToFile",
"(",
"String",
"filename",
")",
"{",
"Logger",
"rootLogger",
"=",
"(",
"Logger",
")",
"LoggerFactory",
".",
"getLogger",
"(",
"org",
".",
"slf4j",
".",
"Logger",
".",
"ROOT_LO... | Configure file logging and stop console logging.
@param filename
Log to this file. | [
"Configure",
"file",
"logging",
"and",
"stop",
"console",
"logging",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/cli/src/main/java/com/crawljax/cli/LogUtil.java#L20-L37 |
160,435 | crawljax/crawljax | cli/src/main/java/com/crawljax/cli/JarRunner.java | JarRunner.main | public static void main(String[] args) {
try {
JarRunner runner = new JarRunner(args);
runner.runIfConfigured();
} catch (NumberFormatException e) {
System.err.println("Could not parse number " + e.getMessage());
System.exit(1);
} catch (RuntimeException e) {
System.err.println(e.getMessage());
System.exit(1);
}
} | java | public static void main(String[] args) {
try {
JarRunner runner = new JarRunner(args);
runner.runIfConfigured();
} catch (NumberFormatException e) {
System.err.println("Could not parse number " + e.getMessage());
System.exit(1);
} catch (RuntimeException e) {
System.err.println(e.getMessage());
System.exit(1);
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"try",
"{",
"JarRunner",
"runner",
"=",
"new",
"JarRunner",
"(",
"args",
")",
";",
"runner",
".",
"runIfConfigured",
"(",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",... | Main executable method of Crawljax CLI.
@param args
the arguments. | [
"Main",
"executable",
"method",
"of",
"Crawljax",
"CLI",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/cli/src/main/java/com/crawljax/cli/JarRunner.java#L37-L48 |
160,436 | crawljax/crawljax | plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/model/Serializer.java | Serializer.toPrettyJson | public static String toPrettyJson(Object o) {
try {
return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(o);
} catch (JsonProcessingException e) {
LoggerFactory
.getLogger(Serializer.class)
.error("Could not serialize the object. This will be ignored and the error will be written instead. Object was {}",
o, e);
return "\"" + e.getMessage() + "\"";
}
} | java | public static String toPrettyJson(Object o) {
try {
return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(o);
} catch (JsonProcessingException e) {
LoggerFactory
.getLogger(Serializer.class)
.error("Could not serialize the object. This will be ignored and the error will be written instead. Object was {}",
o, e);
return "\"" + e.getMessage() + "\"";
}
} | [
"public",
"static",
"String",
"toPrettyJson",
"(",
"Object",
"o",
")",
"{",
"try",
"{",
"return",
"MAPPER",
".",
"writerWithDefaultPrettyPrinter",
"(",
")",
".",
"writeValueAsString",
"(",
"o",
")",
";",
"}",
"catch",
"(",
"JsonProcessingException",
"e",
")",
... | Serialize the object JSON. When an error occures return a string with the given error. | [
"Serialize",
"the",
"object",
"JSON",
".",
"When",
"an",
"error",
"occures",
"return",
"a",
"string",
"with",
"the",
"given",
"error",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/model/Serializer.java#L62-L72 |
160,437 | crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/InfoTree.java | InfoTree.postTraversalProcessing | private void postTraversalProcessing() {
int nc1 = treeSize;
info[KR] = new int[leafCount];
info[RKR] = new int[leafCount];
int lc = leafCount;
int i = 0;
// compute left-most leaf descendants
// go along the left-most path, remember each node and assign to it the path's
// leaf
// compute right-most leaf descendants (in reversed postorder)
for (i = 0; i < treeSize; i++) {
if (paths[LEFT][i] == -1) {
info[POST2_LLD][i] = i;
} else {
info[POST2_LLD][i] = info[POST2_LLD][paths[LEFT][i]];
}
if (paths[RIGHT][i] == -1) {
info[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =
(treeSize - 1 - info[POST2_PRE][i]);
} else {
info[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =
info[RPOST2_RLD][treeSize - 1
- info[POST2_PRE][paths[RIGHT][i]]];
}
}
// compute key root nodes
// compute reversed key root nodes (in revrsed postorder)
boolean[] visited = new boolean[nc1];
boolean[] visitedR = new boolean[nc1];
Arrays.fill(visited, false);
int k = lc - 1;
int kR = lc - 1;
for (i = nc1 - 1; i >= 0; i--) {
if (!visited[info[POST2_LLD][i]]) {
info[KR][k] = i;
visited[info[POST2_LLD][i]] = true;
k--;
}
if (!visitedR[info[RPOST2_RLD][i]]) {
info[RKR][kR] = i;
visitedR[info[RPOST2_RLD][i]] = true;
kR--;
}
}
// compute minimal key roots for every subtree
// compute minimal reversed key roots for every subtree (in reversed postorder)
int parent = -1;
int parentR = -1;
for (i = 0; i < leafCount; i++) {
parent = info[KR][i];
while (parent > -1 && info[POST2_MIN_KR][parent] == -1) {
info[POST2_MIN_KR][parent] = i;
parent = info[POST2_PARENT][parent];
}
parentR = info[RKR][i];
while (parentR > -1 && info[RPOST2_MIN_RKR][parentR] == -1) {
info[RPOST2_MIN_RKR][parentR] = i;
parentR =
info[POST2_PARENT][info[RPOST2_POST][parentR]]; // get parent's postorder
if (parentR > -1) {
parentR = treeSize - 1 - info[POST2_PRE][parentR]; // if parent exists get its
// rev. postorder
}
}
}
} | java | private void postTraversalProcessing() {
int nc1 = treeSize;
info[KR] = new int[leafCount];
info[RKR] = new int[leafCount];
int lc = leafCount;
int i = 0;
// compute left-most leaf descendants
// go along the left-most path, remember each node and assign to it the path's
// leaf
// compute right-most leaf descendants (in reversed postorder)
for (i = 0; i < treeSize; i++) {
if (paths[LEFT][i] == -1) {
info[POST2_LLD][i] = i;
} else {
info[POST2_LLD][i] = info[POST2_LLD][paths[LEFT][i]];
}
if (paths[RIGHT][i] == -1) {
info[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =
(treeSize - 1 - info[POST2_PRE][i]);
} else {
info[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =
info[RPOST2_RLD][treeSize - 1
- info[POST2_PRE][paths[RIGHT][i]]];
}
}
// compute key root nodes
// compute reversed key root nodes (in revrsed postorder)
boolean[] visited = new boolean[nc1];
boolean[] visitedR = new boolean[nc1];
Arrays.fill(visited, false);
int k = lc - 1;
int kR = lc - 1;
for (i = nc1 - 1; i >= 0; i--) {
if (!visited[info[POST2_LLD][i]]) {
info[KR][k] = i;
visited[info[POST2_LLD][i]] = true;
k--;
}
if (!visitedR[info[RPOST2_RLD][i]]) {
info[RKR][kR] = i;
visitedR[info[RPOST2_RLD][i]] = true;
kR--;
}
}
// compute minimal key roots for every subtree
// compute minimal reversed key roots for every subtree (in reversed postorder)
int parent = -1;
int parentR = -1;
for (i = 0; i < leafCount; i++) {
parent = info[KR][i];
while (parent > -1 && info[POST2_MIN_KR][parent] == -1) {
info[POST2_MIN_KR][parent] = i;
parent = info[POST2_PARENT][parent];
}
parentR = info[RKR][i];
while (parentR > -1 && info[RPOST2_MIN_RKR][parentR] == -1) {
info[RPOST2_MIN_RKR][parentR] = i;
parentR =
info[POST2_PARENT][info[RPOST2_POST][parentR]]; // get parent's postorder
if (parentR > -1) {
parentR = treeSize - 1 - info[POST2_PRE][parentR]; // if parent exists get its
// rev. postorder
}
}
}
} | [
"private",
"void",
"postTraversalProcessing",
"(",
")",
"{",
"int",
"nc1",
"=",
"treeSize",
";",
"info",
"[",
"KR",
"]",
"=",
"new",
"int",
"[",
"leafCount",
"]",
";",
"info",
"[",
"RKR",
"]",
"=",
"new",
"int",
"[",
"leafCount",
"]",
";",
"int",
"... | Gathers information, that couldn't be collected while tree traversal. | [
"Gathers",
"information",
"that",
"couldn",
"t",
"be",
"collected",
"while",
"tree",
"traversal",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/InfoTree.java#L357-L426 |
160,438 | crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/InfoTree.java | InfoTree.toIntArray | static int[] toIntArray(List<Integer> integers) {
int[] ints = new int[integers.size()];
int i = 0;
for (Integer n : integers) {
ints[i++] = n;
}
return ints;
} | java | static int[] toIntArray(List<Integer> integers) {
int[] ints = new int[integers.size()];
int i = 0;
for (Integer n : integers) {
ints[i++] = n;
}
return ints;
} | [
"static",
"int",
"[",
"]",
"toIntArray",
"(",
"List",
"<",
"Integer",
">",
"integers",
")",
"{",
"int",
"[",
"]",
"ints",
"=",
"new",
"int",
"[",
"integers",
".",
"size",
"(",
")",
"]",
";",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"Integer",
"n"... | Transforms a list of Integer objects to an array of primitive int values.
@param integers
@return | [
"Transforms",
"a",
"list",
"of",
"Integer",
"objects",
"to",
"an",
"array",
"of",
"primitive",
"int",
"values",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/InfoTree.java#L434-L441 |
160,439 | crawljax/crawljax | plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java | CrawlOverview.onNewState | @Override
public void onNewState(CrawlerContext context, StateVertex vertex) {
LOG.debug("onNewState");
StateBuilder state = outModelCache.addStateIfAbsent(vertex);
visitedStates.putIfAbsent(state.getName(), vertex);
saveScreenshot(context.getBrowser(), state.getName(), vertex);
outputBuilder.persistDom(state.getName(), context.getBrowser().getUnStrippedDom());
} | java | @Override
public void onNewState(CrawlerContext context, StateVertex vertex) {
LOG.debug("onNewState");
StateBuilder state = outModelCache.addStateIfAbsent(vertex);
visitedStates.putIfAbsent(state.getName(), vertex);
saveScreenshot(context.getBrowser(), state.getName(), vertex);
outputBuilder.persistDom(state.getName(), context.getBrowser().getUnStrippedDom());
} | [
"@",
"Override",
"public",
"void",
"onNewState",
"(",
"CrawlerContext",
"context",
",",
"StateVertex",
"vertex",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"onNewState\"",
")",
";",
"StateBuilder",
"state",
"=",
"outModelCache",
".",
"addStateIfAbsent",
"(",
"vertex"... | Saves a screenshot of every new state. | [
"Saves",
"a",
"screenshot",
"of",
"every",
"new",
"state",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java#L91-L100 |
160,440 | crawljax/crawljax | plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java | CrawlOverview.preStateCrawling | @Override
public void preStateCrawling(CrawlerContext context,
ImmutableList<CandidateElement> candidateElements, StateVertex state) {
LOG.debug("preStateCrawling");
List<CandidateElementPosition> newElements = Lists.newLinkedList();
LOG.info("Prestate found new state {} with {} candidates", state.getName(),
candidateElements.size());
for (CandidateElement element : candidateElements) {
try {
WebElement webElement = getWebElement(context.getBrowser(), element);
if (webElement != null) {
newElements.add(findElement(webElement, element));
}
} catch (WebDriverException e) {
LOG.info("Could not get position for {}", element, e);
}
}
StateBuilder stateOut = outModelCache.addStateIfAbsent(state);
stateOut.addCandidates(newElements);
LOG.trace("preState finished, elements added to state");
} | java | @Override
public void preStateCrawling(CrawlerContext context,
ImmutableList<CandidateElement> candidateElements, StateVertex state) {
LOG.debug("preStateCrawling");
List<CandidateElementPosition> newElements = Lists.newLinkedList();
LOG.info("Prestate found new state {} with {} candidates", state.getName(),
candidateElements.size());
for (CandidateElement element : candidateElements) {
try {
WebElement webElement = getWebElement(context.getBrowser(), element);
if (webElement != null) {
newElements.add(findElement(webElement, element));
}
} catch (WebDriverException e) {
LOG.info("Could not get position for {}", element, e);
}
}
StateBuilder stateOut = outModelCache.addStateIfAbsent(state);
stateOut.addCandidates(newElements);
LOG.trace("preState finished, elements added to state");
} | [
"@",
"Override",
"public",
"void",
"preStateCrawling",
"(",
"CrawlerContext",
"context",
",",
"ImmutableList",
"<",
"CandidateElement",
">",
"candidateElements",
",",
"StateVertex",
"state",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"preStateCrawling\"",
")",
";",
"Li... | Logs all the canidate elements so that the plugin knows which elements were the candidate
elements. | [
"Logs",
"all",
"the",
"canidate",
"elements",
"so",
"that",
"the",
"plugin",
"knows",
"which",
"elements",
"were",
"the",
"candidate",
"elements",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java#L139-L160 |
160,441 | crawljax/crawljax | plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java | CrawlOverview.postCrawling | @Override
public void postCrawling(CrawlSession session, ExitStatus exitStatus) {
LOG.debug("postCrawling");
StateFlowGraph sfg = session.getStateFlowGraph();
checkSFG(sfg);
// TODO: call state abstraction function to get distance matrix and run rscript on it to
// create clusters
String[][] clusters = null;
// generateClusters(session);
result = outModelCache.close(session, exitStatus, clusters);
outputBuilder.write(result, session.getConfig(), clusters);
StateWriter writer =
new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));
for (State state : result.getStates().values()) {
try {
writer.writeHtmlForState(state);
} catch (Exception Ex) {
LOG.info("couldn't write state :" + state.getName());
}
}
LOG.info("Crawl overview plugin has finished");
} | java | @Override
public void postCrawling(CrawlSession session, ExitStatus exitStatus) {
LOG.debug("postCrawling");
StateFlowGraph sfg = session.getStateFlowGraph();
checkSFG(sfg);
// TODO: call state abstraction function to get distance matrix and run rscript on it to
// create clusters
String[][] clusters = null;
// generateClusters(session);
result = outModelCache.close(session, exitStatus, clusters);
outputBuilder.write(result, session.getConfig(), clusters);
StateWriter writer =
new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));
for (State state : result.getStates().values()) {
try {
writer.writeHtmlForState(state);
} catch (Exception Ex) {
LOG.info("couldn't write state :" + state.getName());
}
}
LOG.info("Crawl overview plugin has finished");
} | [
"@",
"Override",
"public",
"void",
"postCrawling",
"(",
"CrawlSession",
"session",
",",
"ExitStatus",
"exitStatus",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"postCrawling\"",
")",
";",
"StateFlowGraph",
"sfg",
"=",
"session",
".",
"getStateFlowGraph",
"(",
")",
"... | Generated the report. | [
"Generated",
"the",
"report",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java#L199-L222 |
160,442 | crawljax/crawljax | core/src/main/java/com/crawljax/core/configuration/InputSpecification.java | InputSpecification.setValuesInForm | public FormAction setValuesInForm(Form form) {
FormAction formAction = new FormAction();
form.setFormAction(formAction);
this.forms.add(form);
return formAction;
} | java | public FormAction setValuesInForm(Form form) {
FormAction formAction = new FormAction();
form.setFormAction(formAction);
this.forms.add(form);
return formAction;
} | [
"public",
"FormAction",
"setValuesInForm",
"(",
"Form",
"form",
")",
"{",
"FormAction",
"formAction",
"=",
"new",
"FormAction",
"(",
")",
";",
"form",
".",
"setFormAction",
"(",
"formAction",
")",
";",
"this",
".",
"forms",
".",
"add",
"(",
"form",
")",
... | Links the form with an HTML element which can be clicked.
@param form the collection of the input fields
@return a FormAction
@see Form | [
"Links",
"the",
"form",
"with",
"an",
"HTML",
"element",
"which",
"can",
"be",
"clicked",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/configuration/InputSpecification.java#L73-L78 |
160,443 | crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.removeTags | public static Document removeTags(Document dom, String tagName) {
NodeList list;
try {
list = XPathHelper.evaluateXpathExpression(dom,
"//" + tagName.toUpperCase());
while (list.getLength() > 0) {
Node sc = list.item(0);
if (sc != null) {
sc.getParentNode().removeChild(sc);
}
list = XPathHelper.evaluateXpathExpression(dom,
"//" + tagName.toUpperCase());
}
} catch (XPathExpressionException e) {
LOGGER.error("Error while removing tag " + tagName, e);
}
return dom;
} | java | public static Document removeTags(Document dom, String tagName) {
NodeList list;
try {
list = XPathHelper.evaluateXpathExpression(dom,
"//" + tagName.toUpperCase());
while (list.getLength() > 0) {
Node sc = list.item(0);
if (sc != null) {
sc.getParentNode().removeChild(sc);
}
list = XPathHelper.evaluateXpathExpression(dom,
"//" + tagName.toUpperCase());
}
} catch (XPathExpressionException e) {
LOGGER.error("Error while removing tag " + tagName, e);
}
return dom;
} | [
"public",
"static",
"Document",
"removeTags",
"(",
"Document",
"dom",
",",
"String",
"tagName",
")",
"{",
"NodeList",
"list",
";",
"try",
"{",
"list",
"=",
"XPathHelper",
".",
"evaluateXpathExpression",
"(",
"dom",
",",
"\"//\"",
"+",
"tagName",
".",
"toUppe... | Removes all the given tags from the document.
@param dom the document object.
@param tagName the tag name, examples: script, style, meta
@return the changed dom. | [
"Removes",
"all",
"the",
"given",
"tags",
"from",
"the",
"document",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L171-L193 |
160,444 | crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.getDocumentToByteArray | public static byte[] getDocumentToByteArray(Document dom) {
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer
.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "html");
// TODO should be fixed to read doctype declaration
transformer
.setOutputProperty(
OutputKeys.DOCTYPE_PUBLIC,
"-//W3C//DTD XHTML 1.0 Strict//EN\" "
+ "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
DOMSource source = new DOMSource(dom);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Result result = new StreamResult(out);
transformer.transform(source, result);
return out.toByteArray();
} catch (TransformerException e) {
LOGGER.error("Error while converting the document to a byte array",
e);
}
return null;
} | java | public static byte[] getDocumentToByteArray(Document dom) {
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer
.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "html");
// TODO should be fixed to read doctype declaration
transformer
.setOutputProperty(
OutputKeys.DOCTYPE_PUBLIC,
"-//W3C//DTD XHTML 1.0 Strict//EN\" "
+ "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
DOMSource source = new DOMSource(dom);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Result result = new StreamResult(out);
transformer.transform(source, result);
return out.toByteArray();
} catch (TransformerException e) {
LOGGER.error("Error while converting the document to a byte array",
e);
}
return null;
} | [
"public",
"static",
"byte",
"[",
"]",
"getDocumentToByteArray",
"(",
"Document",
"dom",
")",
"{",
"try",
"{",
"TransformerFactory",
"tFactory",
"=",
"TransformerFactory",
".",
"newInstance",
"(",
")",
";",
"Transformer",
"transformer",
"=",
"tFactory",
".",
"new... | Serialize the Document object.
@param dom the document to serialize
@return the serialized dom String | [
"Serialize",
"the",
"Document",
"object",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L224-L253 |
160,445 | crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.addFolderSlashIfNeeded | public static String addFolderSlashIfNeeded(String folderName) {
if (!"".equals(folderName) && !folderName.endsWith("/")) {
return folderName + "/";
} else {
return folderName;
}
} | java | public static String addFolderSlashIfNeeded(String folderName) {
if (!"".equals(folderName) && !folderName.endsWith("/")) {
return folderName + "/";
} else {
return folderName;
}
} | [
"public",
"static",
"String",
"addFolderSlashIfNeeded",
"(",
"String",
"folderName",
")",
"{",
"if",
"(",
"!",
"\"\"",
".",
"equals",
"(",
"folderName",
")",
"&&",
"!",
"folderName",
".",
"endsWith",
"(",
"\"/\"",
")",
")",
"{",
"return",
"folderName",
"+"... | Adds a slash to a path if it doesn't end with a slash.
@param folderName The path to append a possible slash.
@return The new, correct path. | [
"Adds",
"a",
"slash",
"to",
"a",
"path",
"if",
"it",
"doesn",
"t",
"end",
"with",
"a",
"slash",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L349-L355 |
160,446 | crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.getTemplateAsString | public static String getTemplateAsString(String fileName) throws IOException {
// in .jar file
String fNameJar = getFileNameInPath(fileName);
InputStream inStream = DomUtils.class.getResourceAsStream("/"
+ fNameJar);
if (inStream == null) {
// try to find file normally
File f = new File(fileName);
if (f.exists()) {
inStream = new FileInputStream(f);
} else {
throw new IOException("Cannot find " + fileName + " or "
+ fNameJar);
}
}
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inStream));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} | java | public static String getTemplateAsString(String fileName) throws IOException {
// in .jar file
String fNameJar = getFileNameInPath(fileName);
InputStream inStream = DomUtils.class.getResourceAsStream("/"
+ fNameJar);
if (inStream == null) {
// try to find file normally
File f = new File(fileName);
if (f.exists()) {
inStream = new FileInputStream(f);
} else {
throw new IOException("Cannot find " + fileName + " or "
+ fNameJar);
}
}
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inStream));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} | [
"public",
"static",
"String",
"getTemplateAsString",
"(",
"String",
"fileName",
")",
"throws",
"IOException",
"{",
"// in .jar file",
"String",
"fNameJar",
"=",
"getFileNameInPath",
"(",
"fileName",
")",
";",
"InputStream",
"inStream",
"=",
"DomUtils",
".",
"class",... | Retrieves the content of the filename. Also reads from JAR Searches for the resource in the
root folder in the jar
@param fileName Filename.
@return The contents of the file.
@throws IOException On error. | [
"Retrieves",
"the",
"content",
"of",
"the",
"filename",
".",
"Also",
"reads",
"from",
"JAR",
"Searches",
"for",
"the",
"resource",
"in",
"the",
"root",
"folder",
"in",
"the",
"jar"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L382-L409 |
160,447 | crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.writeDocumentToFile | public static void writeDocumentToFile(Document document,
String filePathname, String method, int indent)
throws TransformerException, IOException {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, method);
transformer.transform(new DOMSource(document), new StreamResult(
new FileOutputStream(filePathname)));
} | java | public static void writeDocumentToFile(Document document,
String filePathname, String method, int indent)
throws TransformerException, IOException {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, method);
transformer.transform(new DOMSource(document), new StreamResult(
new FileOutputStream(filePathname)));
} | [
"public",
"static",
"void",
"writeDocumentToFile",
"(",
"Document",
"document",
",",
"String",
"filePathname",
",",
"String",
"method",
",",
"int",
"indent",
")",
"throws",
"TransformerException",
",",
"IOException",
"{",
"Transformer",
"transformer",
"=",
"Transfor... | Write the document object to a file.
@param document the document object.
@param filePathname the path name of the file to be written to.
@param method the output method: for instance html, xml, text
@param indent amount of indentation. -1 to use the default.
@throws TransformerException if an exception occurs.
@throws IOException if an IO exception occurs. | [
"Write",
"the",
"document",
"object",
"to",
"a",
"file",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L443-L455 |
160,448 | crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.getTextContent | public static String getTextContent(Document document, boolean individualTokens) {
String textContent = null;
if (individualTokens) {
List<String> tokens = getTextTokens(document);
textContent = StringUtils.join(tokens, ",");
} else {
textContent =
document.getDocumentElement().getTextContent().trim().replaceAll("\\s+", ",");
}
return textContent;
} | java | public static String getTextContent(Document document, boolean individualTokens) {
String textContent = null;
if (individualTokens) {
List<String> tokens = getTextTokens(document);
textContent = StringUtils.join(tokens, ",");
} else {
textContent =
document.getDocumentElement().getTextContent().trim().replaceAll("\\s+", ",");
}
return textContent;
} | [
"public",
"static",
"String",
"getTextContent",
"(",
"Document",
"document",
",",
"boolean",
"individualTokens",
")",
"{",
"String",
"textContent",
"=",
"null",
";",
"if",
"(",
"individualTokens",
")",
"{",
"List",
"<",
"String",
">",
"tokens",
"=",
"getTextTo... | To get all the textual content in the dom
@param document
@param individualTokens : default True : when set to true, each text node from dom is used to build the
text content : when set to false, the text content of whole is obtained at once.
@return | [
"To",
"get",
"all",
"the",
"textual",
"content",
"in",
"the",
"dom"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L511-L521 |
160,449 | crawljax/crawljax | core/src/main/java/com/crawljax/util/ElementResolver.java | ElementResolver.equivalent | public boolean equivalent(Element otherElement, boolean logging) {
if (eventable.getElement().equals(otherElement)) {
if (logging) {
LOGGER.info("Element equal");
}
return true;
}
if (eventable.getElement().equalAttributes(otherElement)) {
if (logging) {
LOGGER.info("Element attributes equal");
}
return true;
}
if (eventable.getElement().equalId(otherElement)) {
if (logging) {
LOGGER.info("Element ID equal");
}
return true;
}
if (!eventable.getElement().getText().equals("")
&& eventable.getElement().equalText(otherElement)) {
if (logging) {
LOGGER.info("Element text equal");
}
return true;
}
return false;
} | java | public boolean equivalent(Element otherElement, boolean logging) {
if (eventable.getElement().equals(otherElement)) {
if (logging) {
LOGGER.info("Element equal");
}
return true;
}
if (eventable.getElement().equalAttributes(otherElement)) {
if (logging) {
LOGGER.info("Element attributes equal");
}
return true;
}
if (eventable.getElement().equalId(otherElement)) {
if (logging) {
LOGGER.info("Element ID equal");
}
return true;
}
if (!eventable.getElement().getText().equals("")
&& eventable.getElement().equalText(otherElement)) {
if (logging) {
LOGGER.info("Element text equal");
}
return true;
}
return false;
} | [
"public",
"boolean",
"equivalent",
"(",
"Element",
"otherElement",
",",
"boolean",
"logging",
")",
"{",
"if",
"(",
"eventable",
".",
"getElement",
"(",
")",
".",
"equals",
"(",
"otherElement",
")",
")",
"{",
"if",
"(",
"logging",
")",
"{",
"LOGGER",
".",... | Comparator against other element.
@param otherElement The other element.
@param logging Whether to do logging.
@return Whether the elements are equal. | [
"Comparator",
"against",
"other",
"element",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/ElementResolver.java#L105-L138 |
160,450 | crawljax/crawljax | core/src/main/java/com/crawljax/util/DOMComparer.java | DOMComparer.compare | @SuppressWarnings("unchecked")
public List<Difference> compare() {
Diff diff = new Diff(this.controlDOM, this.testDOM);
DetailedDiff detDiff = new DetailedDiff(diff);
return detDiff.getAllDifferences();
} | java | @SuppressWarnings("unchecked")
public List<Difference> compare() {
Diff diff = new Diff(this.controlDOM, this.testDOM);
DetailedDiff detDiff = new DetailedDiff(diff);
return detDiff.getAllDifferences();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"List",
"<",
"Difference",
">",
"compare",
"(",
")",
"{",
"Diff",
"diff",
"=",
"new",
"Diff",
"(",
"this",
".",
"controlDOM",
",",
"this",
".",
"testDOM",
")",
";",
"DetailedDiff",
"detDiff",
... | Compare the controlDOM and testDOM and save and return the differences in a list.
@return list with differences | [
"Compare",
"the",
"controlDOM",
"and",
"testDOM",
"and",
"save",
"and",
"return",
"the",
"differences",
"in",
"a",
"list",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DOMComparer.java#L42-L47 |
160,451 | 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 |
160,452 | 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 |
160,453 | 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 |
160,454 | 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 |
160,455 | 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 |
160,456 | 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 |
160,457 | 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 |
160,458 | 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 |
160,459 | 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 |
160,460 | 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 |
160,461 | 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 |
160,462 | 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 |
160,463 | 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 |
160,464 | 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 |
160,465 | 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 |
160,466 | 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 |
160,467 | 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 |
160,468 | 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 |
160,469 | 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 |
160,470 | 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 |
160,471 | 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 |
160,472 | 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 |
160,473 | 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 |
160,474 | 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 |
160,475 | 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 |
160,476 | 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 |
160,477 | 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 |
160,478 | 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 |
160,479 | 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 |
160,480 | 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 |
160,481 | 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 |
160,482 | 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 |
160,483 | 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 |
160,484 | 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 |
160,485 | 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 |
160,486 | 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 |
160,487 | 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 |
160,488 | 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 |
160,489 | 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 |
160,490 | 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 |
160,491 | 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 |
160,492 | 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 |
160,493 | 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 |
160,494 | 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 |
160,495 | 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 |
160,496 | 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 |
160,497 | 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 |
160,498 | 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 |
160,499 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.