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
19,200
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/MultiDocumentsHandler.java
MultiDocumentsHandler.getNumDoc
private int getNumDoc(String docID) { if (goneContext != null ) { removeDoc(docID); } for (int i = 0; i < documents.size(); i++) { if (documents.get(i).getDocID().equals(docID)) { // document exist if(!testMode && documents.get(i).getXComponent() == null) { XComponent xComponent = OfficeTools.getCurrentComponent(xContext); if (xComponent == null) { MessageHandler.printToLogFile("Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes"); } else { try { xComponent.addEventListener(xEventListener); } catch (Throwable t) { MessageHandler.printToLogFile("Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes"); xComponent = null; } if(xComponent != null) { documents.get(i).setXComponent(xContext, xComponent); MessageHandler.printToLogFile("Fixed: XComponent set for Document (ID: " + docID + ")"); } } } return i; } } // Add new document XComponent xComponent = null; if (!testMode) { // xComponent == null for test cases xComponent = OfficeTools.getCurrentComponent(xContext); if (xComponent == null) { MessageHandler.printToLogFile("Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes"); } else { try { xComponent.addEventListener(xEventListener); } catch (Throwable t) { MessageHandler.printToLogFile("Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes"); xComponent = null; } } } documents.add(new SingleDocument(xContext, config, docID, xComponent)); setMenuTextForSwitchOff(xContext); if (debugMode) { MessageHandler.printToLogFile("Document " + docNum + " created; docID = " + docID); } return documents.size() - 1; }
java
private int getNumDoc(String docID) { if (goneContext != null ) { removeDoc(docID); } for (int i = 0; i < documents.size(); i++) { if (documents.get(i).getDocID().equals(docID)) { // document exist if(!testMode && documents.get(i).getXComponent() == null) { XComponent xComponent = OfficeTools.getCurrentComponent(xContext); if (xComponent == null) { MessageHandler.printToLogFile("Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes"); } else { try { xComponent.addEventListener(xEventListener); } catch (Throwable t) { MessageHandler.printToLogFile("Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes"); xComponent = null; } if(xComponent != null) { documents.get(i).setXComponent(xContext, xComponent); MessageHandler.printToLogFile("Fixed: XComponent set for Document (ID: " + docID + ")"); } } } return i; } } // Add new document XComponent xComponent = null; if (!testMode) { // xComponent == null for test cases xComponent = OfficeTools.getCurrentComponent(xContext); if (xComponent == null) { MessageHandler.printToLogFile("Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes"); } else { try { xComponent.addEventListener(xEventListener); } catch (Throwable t) { MessageHandler.printToLogFile("Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes"); xComponent = null; } } } documents.add(new SingleDocument(xContext, config, docID, xComponent)); setMenuTextForSwitchOff(xContext); if (debugMode) { MessageHandler.printToLogFile("Document " + docNum + " created; docID = " + docID); } return documents.size() - 1; }
[ "private", "int", "getNumDoc", "(", "String", "docID", ")", "{", "if", "(", "goneContext", "!=", "null", ")", "{", "removeDoc", "(", "docID", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "documents", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "documents", ".", "get", "(", "i", ")", ".", "getDocID", "(", ")", ".", "equals", "(", "docID", ")", ")", "{", "// document exist", "if", "(", "!", "testMode", "&&", "documents", ".", "get", "(", "i", ")", ".", "getXComponent", "(", ")", "==", "null", ")", "{", "XComponent", "xComponent", "=", "OfficeTools", ".", "getCurrentComponent", "(", "xContext", ")", ";", "if", "(", "xComponent", "==", "null", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"Error: Document (ID: \"", "+", "docID", "+", "\") has no XComponent -> Internal space will not be deleted when document disposes\"", ")", ";", "}", "else", "{", "try", "{", "xComponent", ".", "addEventListener", "(", "xEventListener", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"Error: Document (ID: \"", "+", "docID", "+", "\") has no XComponent -> Internal space will not be deleted when document disposes\"", ")", ";", "xComponent", "=", "null", ";", "}", "if", "(", "xComponent", "!=", "null", ")", "{", "documents", ".", "get", "(", "i", ")", ".", "setXComponent", "(", "xContext", ",", "xComponent", ")", ";", "MessageHandler", ".", "printToLogFile", "(", "\"Fixed: XComponent set for Document (ID: \"", "+", "docID", "+", "\")\"", ")", ";", "}", "}", "}", "return", "i", ";", "}", "}", "// Add new document", "XComponent", "xComponent", "=", "null", ";", "if", "(", "!", "testMode", ")", "{", "// xComponent == null for test cases ", "xComponent", "=", "OfficeTools", ".", "getCurrentComponent", "(", "xContext", ")", ";", "if", "(", "xComponent", "==", "null", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"Error: Document (ID: \"", "+", "docID", "+", "\") has no XComponent -> Internal space will not be deleted when document disposes\"", ")", ";", "}", "else", "{", "try", "{", "xComponent", ".", "addEventListener", "(", "xEventListener", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"Error: Document (ID: \"", "+", "docID", "+", "\") has no XComponent -> Internal space will not be deleted when document disposes\"", ")", ";", "xComponent", "=", "null", ";", "}", "}", "}", "documents", ".", "add", "(", "new", "SingleDocument", "(", "xContext", ",", "config", ",", "docID", ",", "xComponent", ")", ")", ";", "setMenuTextForSwitchOff", "(", "xContext", ")", ";", "if", "(", "debugMode", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"Document \"", "+", "docNum", "+", "\" created; docID = \"", "+", "docID", ")", ";", "}", "return", "documents", ".", "size", "(", ")", "-", "1", ";", "}" ]
Get or Create a Number from docID Return -1 if failed
[ "Get", "or", "Create", "a", "Number", "from", "docID", "Return", "-", "1", "if", "failed" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/MultiDocumentsHandler.java#L330-L377
19,201
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/MultiDocumentsHandler.java
MultiDocumentsHandler.removeDoc
private void removeDoc(String docID) { int rmNum = -1; int docNum = -1; for (int i = 0; i < documents.size(); i++) { XComponent xComponent = documents.get(i).getXComponent(); if (xComponent != null && xComponent.equals(goneContext)) { // disposed document found rmNum = i; break; } } if(rmNum < 0) { MessageHandler.printToLogFile("Error: Disposed document not found"); goneContext = null; } for (int i = 0; i < documents.size(); i++) { if (documents.get(i).getDocID().equals(docID)) { // document exist docNum = i; break; } } if(rmNum >= 0 && docNum != rmNum ) { // don't delete a closed document before the last check is done documents.remove(rmNum); goneContext = null; if (debugMode) { MessageHandler.printToLogFile("Document " + rmNum + " deleted"); } } }
java
private void removeDoc(String docID) { int rmNum = -1; int docNum = -1; for (int i = 0; i < documents.size(); i++) { XComponent xComponent = documents.get(i).getXComponent(); if (xComponent != null && xComponent.equals(goneContext)) { // disposed document found rmNum = i; break; } } if(rmNum < 0) { MessageHandler.printToLogFile("Error: Disposed document not found"); goneContext = null; } for (int i = 0; i < documents.size(); i++) { if (documents.get(i).getDocID().equals(docID)) { // document exist docNum = i; break; } } if(rmNum >= 0 && docNum != rmNum ) { // don't delete a closed document before the last check is done documents.remove(rmNum); goneContext = null; if (debugMode) { MessageHandler.printToLogFile("Document " + rmNum + " deleted"); } } }
[ "private", "void", "removeDoc", "(", "String", "docID", ")", "{", "int", "rmNum", "=", "-", "1", ";", "int", "docNum", "=", "-", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "documents", ".", "size", "(", ")", ";", "i", "++", ")", "{", "XComponent", "xComponent", "=", "documents", ".", "get", "(", "i", ")", ".", "getXComponent", "(", ")", ";", "if", "(", "xComponent", "!=", "null", "&&", "xComponent", ".", "equals", "(", "goneContext", ")", ")", "{", "// disposed document found", "rmNum", "=", "i", ";", "break", ";", "}", "}", "if", "(", "rmNum", "<", "0", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"Error: Disposed document not found\"", ")", ";", "goneContext", "=", "null", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "documents", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "documents", ".", "get", "(", "i", ")", ".", "getDocID", "(", ")", ".", "equals", "(", "docID", ")", ")", "{", "// document exist", "docNum", "=", "i", ";", "break", ";", "}", "}", "if", "(", "rmNum", ">=", "0", "&&", "docNum", "!=", "rmNum", ")", "{", "// don't delete a closed document before the last check is done", "documents", ".", "remove", "(", "rmNum", ")", ";", "goneContext", "=", "null", ";", "if", "(", "debugMode", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"Document \"", "+", "rmNum", "+", "\" deleted\"", ")", ";", "}", "}", "}" ]
Delete a document number and all internal space
[ "Delete", "a", "document", "number", "and", "all", "internal", "space" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/MultiDocumentsHandler.java#L382-L409
19,202
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/MultiDocumentsHandler.java
MultiDocumentsHandler.setMenuTextForSwitchOff
public boolean setMenuTextForSwitchOff(XComponentContext xContext) { boolean ret = true; XMenuBar menubar = OfficeTools.getMenuBar(xContext); if (menubar == null) { MessageHandler.printToLogFile("Menubar is null"); return ret; } XPopupMenu toolsMenu = null; XPopupMenu ltMenu = null; short toolsId = 0; short ltId = 0; try { for (short i = 0; i < menubar.getItemCount(); i++) { toolsId = menubar.getItemId(i); String command = menubar.getCommand(toolsId); if(TOOLS_COMMAND.equals(command)) { toolsMenu = menubar.getPopupMenu(toolsId); break; } } if (toolsMenu == null) { MessageHandler.printToLogFile("Tools Menu is null"); return ret; } for (short i = 0; i < toolsMenu.getItemCount(); i++) { String command = toolsMenu.getCommand(toolsMenu.getItemId(i)); if(WORD_COUNT_COMMAND.equals(command)) { ltId = toolsMenu.getItemId((short) (i - 1)); ltMenu = toolsMenu.getPopupMenu(ltId); break; } } if (ltMenu == null) { MessageHandler.printToLogFile("LT Menu is null"); return ret; } short switchOffId = 0; for (short i = 0; i < ltMenu.getItemCount(); i++) { String command = ltMenu.getCommand(ltMenu.getItemId(i)); if(LT_SWITCH_OFF_COMMAND.equals(command)) { switchOffId = ltMenu.getItemId(i); break; } } if (switchOffId == 0) { MessageHandler.printToLogFile("switchOffId not found"); return ret; } boolean isSwitchOff = ltMenu.isItemChecked(switchOffId); if((switchOff && isSwitchOff) || (!switchOff && !isSwitchOff)) { ret = false; } ltMenu.setItemText(switchOffId, messages.getString("loMenuSwitchOff")); if(switchOff) { ltMenu.checkItem(switchOffId, true); } else { ltMenu.checkItem(switchOffId, false); } } catch (Throwable t) { MessageHandler.printException(t); } toolsMenu.setPopupMenu(ltId, ltMenu); menubar.setPopupMenu(toolsId, toolsMenu); return ret; }
java
public boolean setMenuTextForSwitchOff(XComponentContext xContext) { boolean ret = true; XMenuBar menubar = OfficeTools.getMenuBar(xContext); if (menubar == null) { MessageHandler.printToLogFile("Menubar is null"); return ret; } XPopupMenu toolsMenu = null; XPopupMenu ltMenu = null; short toolsId = 0; short ltId = 0; try { for (short i = 0; i < menubar.getItemCount(); i++) { toolsId = menubar.getItemId(i); String command = menubar.getCommand(toolsId); if(TOOLS_COMMAND.equals(command)) { toolsMenu = menubar.getPopupMenu(toolsId); break; } } if (toolsMenu == null) { MessageHandler.printToLogFile("Tools Menu is null"); return ret; } for (short i = 0; i < toolsMenu.getItemCount(); i++) { String command = toolsMenu.getCommand(toolsMenu.getItemId(i)); if(WORD_COUNT_COMMAND.equals(command)) { ltId = toolsMenu.getItemId((short) (i - 1)); ltMenu = toolsMenu.getPopupMenu(ltId); break; } } if (ltMenu == null) { MessageHandler.printToLogFile("LT Menu is null"); return ret; } short switchOffId = 0; for (short i = 0; i < ltMenu.getItemCount(); i++) { String command = ltMenu.getCommand(ltMenu.getItemId(i)); if(LT_SWITCH_OFF_COMMAND.equals(command)) { switchOffId = ltMenu.getItemId(i); break; } } if (switchOffId == 0) { MessageHandler.printToLogFile("switchOffId not found"); return ret; } boolean isSwitchOff = ltMenu.isItemChecked(switchOffId); if((switchOff && isSwitchOff) || (!switchOff && !isSwitchOff)) { ret = false; } ltMenu.setItemText(switchOffId, messages.getString("loMenuSwitchOff")); if(switchOff) { ltMenu.checkItem(switchOffId, true); } else { ltMenu.checkItem(switchOffId, false); } } catch (Throwable t) { MessageHandler.printException(t); } toolsMenu.setPopupMenu(ltId, ltMenu); menubar.setPopupMenu(toolsId, toolsMenu); return ret; }
[ "public", "boolean", "setMenuTextForSwitchOff", "(", "XComponentContext", "xContext", ")", "{", "boolean", "ret", "=", "true", ";", "XMenuBar", "menubar", "=", "OfficeTools", ".", "getMenuBar", "(", "xContext", ")", ";", "if", "(", "menubar", "==", "null", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"Menubar is null\"", ")", ";", "return", "ret", ";", "}", "XPopupMenu", "toolsMenu", "=", "null", ";", "XPopupMenu", "ltMenu", "=", "null", ";", "short", "toolsId", "=", "0", ";", "short", "ltId", "=", "0", ";", "try", "{", "for", "(", "short", "i", "=", "0", ";", "i", "<", "menubar", ".", "getItemCount", "(", ")", ";", "i", "++", ")", "{", "toolsId", "=", "menubar", ".", "getItemId", "(", "i", ")", ";", "String", "command", "=", "menubar", ".", "getCommand", "(", "toolsId", ")", ";", "if", "(", "TOOLS_COMMAND", ".", "equals", "(", "command", ")", ")", "{", "toolsMenu", "=", "menubar", ".", "getPopupMenu", "(", "toolsId", ")", ";", "break", ";", "}", "}", "if", "(", "toolsMenu", "==", "null", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"Tools Menu is null\"", ")", ";", "return", "ret", ";", "}", "for", "(", "short", "i", "=", "0", ";", "i", "<", "toolsMenu", ".", "getItemCount", "(", ")", ";", "i", "++", ")", "{", "String", "command", "=", "toolsMenu", ".", "getCommand", "(", "toolsMenu", ".", "getItemId", "(", "i", ")", ")", ";", "if", "(", "WORD_COUNT_COMMAND", ".", "equals", "(", "command", ")", ")", "{", "ltId", "=", "toolsMenu", ".", "getItemId", "(", "(", "short", ")", "(", "i", "-", "1", ")", ")", ";", "ltMenu", "=", "toolsMenu", ".", "getPopupMenu", "(", "ltId", ")", ";", "break", ";", "}", "}", "if", "(", "ltMenu", "==", "null", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"LT Menu is null\"", ")", ";", "return", "ret", ";", "}", "short", "switchOffId", "=", "0", ";", "for", "(", "short", "i", "=", "0", ";", "i", "<", "ltMenu", ".", "getItemCount", "(", ")", ";", "i", "++", ")", "{", "String", "command", "=", "ltMenu", ".", "getCommand", "(", "ltMenu", ".", "getItemId", "(", "i", ")", ")", ";", "if", "(", "LT_SWITCH_OFF_COMMAND", ".", "equals", "(", "command", ")", ")", "{", "switchOffId", "=", "ltMenu", ".", "getItemId", "(", "i", ")", ";", "break", ";", "}", "}", "if", "(", "switchOffId", "==", "0", ")", "{", "MessageHandler", ".", "printToLogFile", "(", "\"switchOffId not found\"", ")", ";", "return", "ret", ";", "}", "boolean", "isSwitchOff", "=", "ltMenu", ".", "isItemChecked", "(", "switchOffId", ")", ";", "if", "(", "(", "switchOff", "&&", "isSwitchOff", ")", "||", "(", "!", "switchOff", "&&", "!", "isSwitchOff", ")", ")", "{", "ret", "=", "false", ";", "}", "ltMenu", ".", "setItemText", "(", "switchOffId", ",", "messages", ".", "getString", "(", "\"loMenuSwitchOff\"", ")", ")", ";", "if", "(", "switchOff", ")", "{", "ltMenu", ".", "checkItem", "(", "switchOffId", ",", "true", ")", ";", "}", "else", "{", "ltMenu", ".", "checkItem", "(", "switchOffId", ",", "false", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "MessageHandler", ".", "printException", "(", "t", ")", ";", "}", "toolsMenu", ".", "setPopupMenu", "(", "ltId", ",", "ltMenu", ")", ";", "menubar", ".", "setPopupMenu", "(", "toolsId", ",", "toolsMenu", ")", ";", "return", "ret", ";", "}" ]
Set or remove a check mark to the LT menu item Switch Off return true if text should be rechecked
[ "Set", "or", "remove", "a", "check", "mark", "to", "the", "LT", "menu", "item", "Switch", "Off", "return", "true", "if", "text", "should", "be", "rechecked" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/MultiDocumentsHandler.java#L483-L550
19,203
languagetool-org/languagetool
languagetool-server/src/main/java/org/languagetool/server/PipelinePool.java
PipelinePool.createPipeline
Pipeline createPipeline(Language lang, Language motherTongue, TextChecker.QueryParams params, UserConfig userConfig) throws Exception { // package-private for mocking Pipeline lt = new Pipeline(lang, params.altLanguages, motherTongue, cache, userConfig); lt.setMaxErrorsPerWordRate(config.getMaxErrorsPerWordRate()); if (config.getLanguageModelDir() != null) { lt.activateLanguageModelRules(config.getLanguageModelDir()); } if (config.getWord2VecModelDir () != null) { lt.activateWord2VecModelRules(config.getWord2VecModelDir()); } if (config.getRulesConfigFile() != null) { configureFromRulesFile(lt, lang); } else { configureFromGUI(lt, lang); } if (params.useQuerySettings) { Tools.selectRules(lt, new HashSet<>(params.disabledCategories), new HashSet<>(params.enabledCategories), new HashSet<>(params.disabledRules), new HashSet<>(params.enabledRules), params.useEnabledOnly); } if (pool != null) { lt.setupFinished(); } return lt; }
java
Pipeline createPipeline(Language lang, Language motherTongue, TextChecker.QueryParams params, UserConfig userConfig) throws Exception { // package-private for mocking Pipeline lt = new Pipeline(lang, params.altLanguages, motherTongue, cache, userConfig); lt.setMaxErrorsPerWordRate(config.getMaxErrorsPerWordRate()); if (config.getLanguageModelDir() != null) { lt.activateLanguageModelRules(config.getLanguageModelDir()); } if (config.getWord2VecModelDir () != null) { lt.activateWord2VecModelRules(config.getWord2VecModelDir()); } if (config.getRulesConfigFile() != null) { configureFromRulesFile(lt, lang); } else { configureFromGUI(lt, lang); } if (params.useQuerySettings) { Tools.selectRules(lt, new HashSet<>(params.disabledCategories), new HashSet<>(params.enabledCategories), new HashSet<>(params.disabledRules), new HashSet<>(params.enabledRules), params.useEnabledOnly); } if (pool != null) { lt.setupFinished(); } return lt; }
[ "Pipeline", "createPipeline", "(", "Language", "lang", ",", "Language", "motherTongue", ",", "TextChecker", ".", "QueryParams", "params", ",", "UserConfig", "userConfig", ")", "throws", "Exception", "{", "// package-private for mocking", "Pipeline", "lt", "=", "new", "Pipeline", "(", "lang", ",", "params", ".", "altLanguages", ",", "motherTongue", ",", "cache", ",", "userConfig", ")", ";", "lt", ".", "setMaxErrorsPerWordRate", "(", "config", ".", "getMaxErrorsPerWordRate", "(", ")", ")", ";", "if", "(", "config", ".", "getLanguageModelDir", "(", ")", "!=", "null", ")", "{", "lt", ".", "activateLanguageModelRules", "(", "config", ".", "getLanguageModelDir", "(", ")", ")", ";", "}", "if", "(", "config", ".", "getWord2VecModelDir", "(", ")", "!=", "null", ")", "{", "lt", ".", "activateWord2VecModelRules", "(", "config", ".", "getWord2VecModelDir", "(", ")", ")", ";", "}", "if", "(", "config", ".", "getRulesConfigFile", "(", ")", "!=", "null", ")", "{", "configureFromRulesFile", "(", "lt", ",", "lang", ")", ";", "}", "else", "{", "configureFromGUI", "(", "lt", ",", "lang", ")", ";", "}", "if", "(", "params", ".", "useQuerySettings", ")", "{", "Tools", ".", "selectRules", "(", "lt", ",", "new", "HashSet", "<>", "(", "params", ".", "disabledCategories", ")", ",", "new", "HashSet", "<>", "(", "params", ".", "enabledCategories", ")", ",", "new", "HashSet", "<>", "(", "params", ".", "disabledRules", ")", ",", "new", "HashSet", "<>", "(", "params", ".", "enabledRules", ")", ",", "params", ".", "useEnabledOnly", ")", ";", "}", "if", "(", "pool", "!=", "null", ")", "{", "lt", ".", "setupFinished", "(", ")", ";", "}", "return", "lt", ";", "}" ]
Create a JLanguageTool instance for a specific language, mother tongue, and rule configuration. Uses Pipeline wrapper to safely share objects @param lang the language to be used @param motherTongue the user's mother tongue or {@code null}
[ "Create", "a", "JLanguageTool", "instance", "for", "a", "specific", "language", "mother", "tongue", "and", "rule", "configuration", ".", "Uses", "Pipeline", "wrapper", "to", "safely", "share", "objects" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-server/src/main/java/org/languagetool/server/PipelinePool.java#L185-L208
19,204
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/synthesis/ManualSynthesizer.java
ManualSynthesizer.lookup
public List<String> lookup(String lemma, String posTag) { return mapping.get(lemma + "|" + posTag); }
java
public List<String> lookup(String lemma, String posTag) { return mapping.get(lemma + "|" + posTag); }
[ "public", "List", "<", "String", ">", "lookup", "(", "String", "lemma", ",", "String", "posTag", ")", "{", "return", "mapping", ".", "get", "(", "lemma", "+", "\"|\"", "+", "posTag", ")", ";", "}" ]
Look up a word's inflected form as specified by the lemma and POS tag. @param lemma the lemma to inflect. @param posTag the required POS tag. @return a list with all the inflected forms of the specified lemma having the specified POS tag. If no inflected form is found, the function returns <code>null</code>.
[ "Look", "up", "a", "word", "s", "inflected", "form", "as", "specified", "by", "the", "lemma", "and", "POS", "tag", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/synthesis/ManualSynthesizer.java#L66-L68
19,205
languagetool-org/languagetool
languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/atom/MatchDatabase.java
MatchDatabase.createTables
void createTables() throws SQLException { try (PreparedStatement prepSt = conn.prepareStatement("CREATE TABLE pings (" + " language_code VARCHAR(5) NOT NULL," + " check_date TIMESTAMP NOT NULL" + ")")) { prepSt.executeUpdate(); } try (PreparedStatement prepSt = conn.prepareStatement("CREATE TABLE feed_checks (" + " language_code VARCHAR(5) NOT NULL," + " check_date TIMESTAMP NOT NULL" + ")")) { prepSt.executeUpdate(); } try (PreparedStatement prepSt = conn.prepareStatement("CREATE TABLE feed_matches (" + " id INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," + " language_code VARCHAR(5) NOT NULL," + " title VARCHAR(255) NOT NULL," + " rule_id VARCHAR(255) NOT NULL," + " rule_sub_id VARCHAR(255)," + " rule_description VARCHAR(255) NOT NULL," + " rule_message VARCHAR(255) NOT NULL," + " rule_category VARCHAR(255) NOT NULL," + " error_context VARCHAR(500) NOT NULL," + " edit_date TIMESTAMP NOT NULL," + " diff_id INT NOT NULL," + " fix_date TIMESTAMP," + " fix_diff_id INT" + ")")) { prepSt.executeUpdate(); } }
java
void createTables() throws SQLException { try (PreparedStatement prepSt = conn.prepareStatement("CREATE TABLE pings (" + " language_code VARCHAR(5) NOT NULL," + " check_date TIMESTAMP NOT NULL" + ")")) { prepSt.executeUpdate(); } try (PreparedStatement prepSt = conn.prepareStatement("CREATE TABLE feed_checks (" + " language_code VARCHAR(5) NOT NULL," + " check_date TIMESTAMP NOT NULL" + ")")) { prepSt.executeUpdate(); } try (PreparedStatement prepSt = conn.prepareStatement("CREATE TABLE feed_matches (" + " id INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," + " language_code VARCHAR(5) NOT NULL," + " title VARCHAR(255) NOT NULL," + " rule_id VARCHAR(255) NOT NULL," + " rule_sub_id VARCHAR(255)," + " rule_description VARCHAR(255) NOT NULL," + " rule_message VARCHAR(255) NOT NULL," + " rule_category VARCHAR(255) NOT NULL," + " error_context VARCHAR(500) NOT NULL," + " edit_date TIMESTAMP NOT NULL," + " diff_id INT NOT NULL," + " fix_date TIMESTAMP," + " fix_diff_id INT" + ")")) { prepSt.executeUpdate(); } }
[ "void", "createTables", "(", ")", "throws", "SQLException", "{", "try", "(", "PreparedStatement", "prepSt", "=", "conn", ".", "prepareStatement", "(", "\"CREATE TABLE pings (\"", "+", "\" language_code VARCHAR(5) NOT NULL,\"", "+", "\" check_date TIMESTAMP NOT NULL\"", "+", "\")\"", ")", ")", "{", "prepSt", ".", "executeUpdate", "(", ")", ";", "}", "try", "(", "PreparedStatement", "prepSt", "=", "conn", ".", "prepareStatement", "(", "\"CREATE TABLE feed_checks (\"", "+", "\" language_code VARCHAR(5) NOT NULL,\"", "+", "\" check_date TIMESTAMP NOT NULL\"", "+", "\")\"", ")", ")", "{", "prepSt", ".", "executeUpdate", "(", ")", ";", "}", "try", "(", "PreparedStatement", "prepSt", "=", "conn", ".", "prepareStatement", "(", "\"CREATE TABLE feed_matches (\"", "+", "\" id INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),\"", "+", "\" language_code VARCHAR(5) NOT NULL,\"", "+", "\" title VARCHAR(255) NOT NULL,\"", "+", "\" rule_id VARCHAR(255) NOT NULL,\"", "+", "\" rule_sub_id VARCHAR(255),\"", "+", "\" rule_description VARCHAR(255) NOT NULL,\"", "+", "\" rule_message VARCHAR(255) NOT NULL,\"", "+", "\" rule_category VARCHAR(255) NOT NULL,\"", "+", "\" error_context VARCHAR(500) NOT NULL,\"", "+", "\" edit_date TIMESTAMP NOT NULL,\"", "+", "\" diff_id INT NOT NULL,\"", "+", "\" fix_date TIMESTAMP,\"", "+", "\" fix_diff_id INT\"", "+", "\")\"", ")", ")", "{", "prepSt", ".", "executeUpdate", "(", ")", ";", "}", "}" ]
Use this only for test cases - it's Derby-specific.
[ "Use", "this", "only", "for", "test", "cases", "-", "it", "s", "Derby", "-", "specific", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/atom/MatchDatabase.java#L133-L163
19,206
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/spelling/SpellingCheckRule.java
SpellingCheckRule.ignoreToken
protected boolean ignoreToken(AnalyzedTokenReadings[] tokens, int idx) throws IOException { List<String> words = new ArrayList<>(); for (AnalyzedTokenReadings token : tokens) { words.add(token.getToken()); } return ignoreWord(words, idx); }
java
protected boolean ignoreToken(AnalyzedTokenReadings[] tokens, int idx) throws IOException { List<String> words = new ArrayList<>(); for (AnalyzedTokenReadings token : tokens) { words.add(token.getToken()); } return ignoreWord(words, idx); }
[ "protected", "boolean", "ignoreToken", "(", "AnalyzedTokenReadings", "[", "]", "tokens", ",", "int", "idx", ")", "throws", "IOException", "{", "List", "<", "String", ">", "words", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "AnalyzedTokenReadings", "token", ":", "tokens", ")", "{", "words", ".", "add", "(", "token", ".", "getToken", "(", ")", ")", ";", "}", "return", "ignoreWord", "(", "words", ",", "idx", ")", ";", "}" ]
Returns true iff the token at the given position should be ignored by the spell checker.
[ "Returns", "true", "iff", "the", "token", "at", "the", "given", "position", "should", "be", "ignored", "by", "the", "spell", "checker", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/spelling/SpellingCheckRule.java#L258-L264
19,207
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/spelling/SpellingCheckRule.java
SpellingCheckRule.filterSuggestions
protected void filterSuggestions(List<String> suggestions) { suggestions.removeIf(suggestion -> isProhibited(suggestion)); filterDupes(suggestions); }
java
protected void filterSuggestions(List<String> suggestions) { suggestions.removeIf(suggestion -> isProhibited(suggestion)); filterDupes(suggestions); }
[ "protected", "void", "filterSuggestions", "(", "List", "<", "String", ">", "suggestions", ")", "{", "suggestions", ".", "removeIf", "(", "suggestion", "->", "isProhibited", "(", "suggestion", ")", ")", ";", "filterDupes", "(", "suggestions", ")", ";", "}" ]
Remove prohibited words from suggestions. @since 2.8
[ "Remove", "prohibited", "words", "from", "suggestions", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/spelling/SpellingCheckRule.java#L394-L397
19,208
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/DocumentCursorTools.java
DocumentCursorTools.getParagraphCursor
@Nullable private XParagraphCursor getParagraphCursor(XComponentContext xContext) { try { XTextCursor xCursor = getCursor(xContext); if (xCursor == null) { return null; } return UnoRuntime.queryInterface(XParagraphCursor.class, xCursor); } catch (Throwable t) { MessageHandler.printException(t); // all Exceptions thrown by UnoRuntime.queryInterface are caught return null; // Return null as method failed } }
java
@Nullable private XParagraphCursor getParagraphCursor(XComponentContext xContext) { try { XTextCursor xCursor = getCursor(xContext); if (xCursor == null) { return null; } return UnoRuntime.queryInterface(XParagraphCursor.class, xCursor); } catch (Throwable t) { MessageHandler.printException(t); // all Exceptions thrown by UnoRuntime.queryInterface are caught return null; // Return null as method failed } }
[ "@", "Nullable", "private", "XParagraphCursor", "getParagraphCursor", "(", "XComponentContext", "xContext", ")", "{", "try", "{", "XTextCursor", "xCursor", "=", "getCursor", "(", "xContext", ")", ";", "if", "(", "xCursor", "==", "null", ")", "{", "return", "null", ";", "}", "return", "UnoRuntime", ".", "queryInterface", "(", "XParagraphCursor", ".", "class", ",", "xCursor", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "MessageHandler", ".", "printException", "(", "t", ")", ";", "// all Exceptions thrown by UnoRuntime.queryInterface are caught", "return", "null", ";", "// Return null as method failed", "}", "}" ]
Returns ParagraphCursor from TextCursor Returns null if it fails
[ "Returns", "ParagraphCursor", "from", "TextCursor", "Returns", "null", "if", "it", "fails" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/DocumentCursorTools.java#L98-L110
19,209
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/DocumentCursorTools.java
DocumentCursorTools.getViewCursor
@Nullable private XTextViewCursor getViewCursor(XComponentContext xContext) { try { XComponent xCurrentComponent = OfficeTools.getCurrentComponent(xContext); if (xCurrentComponent == null) { return null; } XModel xModel = UnoRuntime.queryInterface(XModel.class, xCurrentComponent); if (xModel == null) { return null; } XController xController = xModel.getCurrentController(); if (xController == null) { return null; } XTextViewCursorSupplier xViewCursorSupplier = UnoRuntime.queryInterface(XTextViewCursorSupplier.class, xController); if (xViewCursorSupplier == null) { return null; } return xViewCursorSupplier.getViewCursor(); } catch (Throwable t) { MessageHandler.printException(t); // all Exceptions thrown by UnoRuntime.queryInterface are caught return null; // Return null as method failed } }
java
@Nullable private XTextViewCursor getViewCursor(XComponentContext xContext) { try { XComponent xCurrentComponent = OfficeTools.getCurrentComponent(xContext); if (xCurrentComponent == null) { return null; } XModel xModel = UnoRuntime.queryInterface(XModel.class, xCurrentComponent); if (xModel == null) { return null; } XController xController = xModel.getCurrentController(); if (xController == null) { return null; } XTextViewCursorSupplier xViewCursorSupplier = UnoRuntime.queryInterface(XTextViewCursorSupplier.class, xController); if (xViewCursorSupplier == null) { return null; } return xViewCursorSupplier.getViewCursor(); } catch (Throwable t) { MessageHandler.printException(t); // all Exceptions thrown by UnoRuntime.queryInterface are caught return null; // Return null as method failed } }
[ "@", "Nullable", "private", "XTextViewCursor", "getViewCursor", "(", "XComponentContext", "xContext", ")", "{", "try", "{", "XComponent", "xCurrentComponent", "=", "OfficeTools", ".", "getCurrentComponent", "(", "xContext", ")", ";", "if", "(", "xCurrentComponent", "==", "null", ")", "{", "return", "null", ";", "}", "XModel", "xModel", "=", "UnoRuntime", ".", "queryInterface", "(", "XModel", ".", "class", ",", "xCurrentComponent", ")", ";", "if", "(", "xModel", "==", "null", ")", "{", "return", "null", ";", "}", "XController", "xController", "=", "xModel", ".", "getCurrentController", "(", ")", ";", "if", "(", "xController", "==", "null", ")", "{", "return", "null", ";", "}", "XTextViewCursorSupplier", "xViewCursorSupplier", "=", "UnoRuntime", ".", "queryInterface", "(", "XTextViewCursorSupplier", ".", "class", ",", "xController", ")", ";", "if", "(", "xViewCursorSupplier", "==", "null", ")", "{", "return", "null", ";", "}", "return", "xViewCursorSupplier", ".", "getViewCursor", "(", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "MessageHandler", ".", "printException", "(", "t", ")", ";", "// all Exceptions thrown by UnoRuntime.queryInterface are caught", "return", "null", ";", "// Return null as method failed", "}", "}" ]
Returns ViewCursor Returns null if it fails
[ "Returns", "ViewCursor", "Returns", "null", "if", "it", "fails" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/DocumentCursorTools.java#L116-L141
19,210
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/DocumentCursorTools.java
DocumentCursorTools.getNumberOfAllTextParagraphs
int getNumberOfAllTextParagraphs() { try { if (xPCursor == null) { return 0; } xPCursor.gotoStart(false); int nPara = 1; while (xPCursor.gotoNextParagraph(false)) nPara++; return nPara; } catch (Throwable t) { MessageHandler.printException(t); // all Exceptions thrown by UnoRuntime.queryInterface are caught return 0; // Return 0 as method failed } }
java
int getNumberOfAllTextParagraphs() { try { if (xPCursor == null) { return 0; } xPCursor.gotoStart(false); int nPara = 1; while (xPCursor.gotoNextParagraph(false)) nPara++; return nPara; } catch (Throwable t) { MessageHandler.printException(t); // all Exceptions thrown by UnoRuntime.queryInterface are caught return 0; // Return 0 as method failed } }
[ "int", "getNumberOfAllTextParagraphs", "(", ")", "{", "try", "{", "if", "(", "xPCursor", "==", "null", ")", "{", "return", "0", ";", "}", "xPCursor", ".", "gotoStart", "(", "false", ")", ";", "int", "nPara", "=", "1", ";", "while", "(", "xPCursor", ".", "gotoNextParagraph", "(", "false", ")", ")", "nPara", "++", ";", "return", "nPara", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "MessageHandler", ".", "printException", "(", "t", ")", ";", "// all Exceptions thrown by UnoRuntime.queryInterface are caught", "return", "0", ";", "// Return 0 as method failed", "}", "}" ]
Returns Number of all Paragraphs of Document without footnotes etc. Returns 0 if it fails
[ "Returns", "Number", "of", "all", "Paragraphs", "of", "Document", "without", "footnotes", "etc", ".", "Returns", "0", "if", "it", "fails" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/DocumentCursorTools.java#L147-L160
19,211
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/DocumentCursorTools.java
DocumentCursorTools.getViewCursorParagraph
int getViewCursorParagraph() { try { if (xVCursor == null) { return -4; } XText xDocumentText = xVCursor.getText(); if (xDocumentText == null) { return -3; } XTextCursor xModelCursor = xDocumentText.createTextCursorByRange(xVCursor.getStart()); if (xModelCursor == null) { return -2; } XParagraphCursor xParagraphCursor = UnoRuntime.queryInterface( XParagraphCursor.class, xModelCursor); if (xParagraphCursor == null) { return -1; } int pos = 0; while (xParagraphCursor.gotoPreviousParagraph(false)) pos++; return pos; } catch (Throwable t) { MessageHandler.printException(t); // all Exceptions thrown by UnoRuntime.queryInterface are caught return -5; // Return negative value as method failed } }
java
int getViewCursorParagraph() { try { if (xVCursor == null) { return -4; } XText xDocumentText = xVCursor.getText(); if (xDocumentText == null) { return -3; } XTextCursor xModelCursor = xDocumentText.createTextCursorByRange(xVCursor.getStart()); if (xModelCursor == null) { return -2; } XParagraphCursor xParagraphCursor = UnoRuntime.queryInterface( XParagraphCursor.class, xModelCursor); if (xParagraphCursor == null) { return -1; } int pos = 0; while (xParagraphCursor.gotoPreviousParagraph(false)) pos++; return pos; } catch (Throwable t) { MessageHandler.printException(t); // all Exceptions thrown by UnoRuntime.queryInterface are caught return -5; // Return negative value as method failed } }
[ "int", "getViewCursorParagraph", "(", ")", "{", "try", "{", "if", "(", "xVCursor", "==", "null", ")", "{", "return", "-", "4", ";", "}", "XText", "xDocumentText", "=", "xVCursor", ".", "getText", "(", ")", ";", "if", "(", "xDocumentText", "==", "null", ")", "{", "return", "-", "3", ";", "}", "XTextCursor", "xModelCursor", "=", "xDocumentText", ".", "createTextCursorByRange", "(", "xVCursor", ".", "getStart", "(", ")", ")", ";", "if", "(", "xModelCursor", "==", "null", ")", "{", "return", "-", "2", ";", "}", "XParagraphCursor", "xParagraphCursor", "=", "UnoRuntime", ".", "queryInterface", "(", "XParagraphCursor", ".", "class", ",", "xModelCursor", ")", ";", "if", "(", "xParagraphCursor", "==", "null", ")", "{", "return", "-", "1", ";", "}", "int", "pos", "=", "0", ";", "while", "(", "xParagraphCursor", ".", "gotoPreviousParagraph", "(", "false", ")", ")", "pos", "++", ";", "return", "pos", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "MessageHandler", ".", "printException", "(", "t", ")", ";", "// all Exceptions thrown by UnoRuntime.queryInterface are caught", "return", "-", "5", ";", "// Return negative value as method failed", "}", "}" ]
Returns Paragraph number under ViewCursor Returns a negative value if it fails
[ "Returns", "Paragraph", "number", "under", "ViewCursor", "Returns", "a", "negative", "value", "if", "it", "fails" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/DocumentCursorTools.java#L193-L218
19,212
languagetool-org/languagetool
languagetool-commandline/src/main/java/org/languagetool/commandline/CommandLineTools.java
CommandLineTools.tagText
public static void tagText(String contents, JLanguageTool lt) throws IOException { AnalyzedSentence analyzedText; List<String> sentences = lt.sentenceTokenize(contents); for (String sentence : sentences) { analyzedText = lt.getAnalyzedSentence(sentence); System.out.println(analyzedText); } }
java
public static void tagText(String contents, JLanguageTool lt) throws IOException { AnalyzedSentence analyzedText; List<String> sentences = lt.sentenceTokenize(contents); for (String sentence : sentences) { analyzedText = lt.getAnalyzedSentence(sentence); System.out.println(analyzedText); } }
[ "public", "static", "void", "tagText", "(", "String", "contents", ",", "JLanguageTool", "lt", ")", "throws", "IOException", "{", "AnalyzedSentence", "analyzedText", ";", "List", "<", "String", ">", "sentences", "=", "lt", ".", "sentenceTokenize", "(", "contents", ")", ";", "for", "(", "String", "sentence", ":", "sentences", ")", "{", "analyzedText", "=", "lt", ".", "getAnalyzedSentence", "(", "sentence", ")", ";", "System", ".", "out", ".", "println", "(", "analyzedText", ")", ";", "}", "}" ]
Tags text using the LanguageTool tagger, printing results to System.out. @param contents Text to tag. @param lt LanguageTool instance
[ "Tags", "text", "using", "the", "LanguageTool", "tagger", "printing", "results", "to", "System", ".", "out", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-commandline/src/main/java/org/languagetool/commandline/CommandLineTools.java#L62-L69
19,213
languagetool-org/languagetool
languagetool-commandline/src/main/java/org/languagetool/commandline/CommandLineTools.java
CommandLineTools.checkText
public static int checkText(String contents, JLanguageTool lt, boolean isXmlFormat, boolean isJsonFormat, int contextSize, int lineOffset, int prevMatches, StringTools.ApiPrintMode apiMode, boolean listUnknownWords, List<String> unknownWords) throws IOException { if (contextSize == -1) { contextSize = DEFAULT_CONTEXT_SIZE; } long startTime = System.currentTimeMillis(); List<RuleMatch> ruleMatches = lt.check(contents); // adjust line numbers for (RuleMatch r : ruleMatches) { r.setLine(r.getLine() + lineOffset); r.setEndLine(r.getEndLine() + lineOffset); } if (isXmlFormat) { if (listUnknownWords && apiMode == StringTools.ApiPrintMode.NORMAL_API) { unknownWords = lt.getUnknownWords(); } RuleMatchAsXmlSerializer serializer = new RuleMatchAsXmlSerializer(); String xml = serializer.ruleMatchesToXml(ruleMatches, contents, contextSize, apiMode, lt.getLanguage(), unknownWords); PrintStream out = new PrintStream(System.out, true, "UTF-8"); out.print(xml); } else if (isJsonFormat) { RuleMatchesAsJsonSerializer serializer = new RuleMatchesAsJsonSerializer(); String json = serializer.ruleMatchesToJson(ruleMatches, contents, contextSize, new DetectedLanguage(lt.getLanguage(), lt.getLanguage())); PrintStream out = new PrintStream(System.out, true, "UTF-8"); out.print(json); } else { printMatches(ruleMatches, prevMatches, contents, contextSize); } //display stats if it's not in a buffered mode if (apiMode == StringTools.ApiPrintMode.NORMAL_API && !isJsonFormat) { SentenceTokenizer sentenceTokenizer = lt.getLanguage().getSentenceTokenizer(); int sentenceCount = sentenceTokenizer.tokenize(contents).size(); displayTimeStats(startTime, sentenceCount, isXmlFormat); } return ruleMatches.size(); }
java
public static int checkText(String contents, JLanguageTool lt, boolean isXmlFormat, boolean isJsonFormat, int contextSize, int lineOffset, int prevMatches, StringTools.ApiPrintMode apiMode, boolean listUnknownWords, List<String> unknownWords) throws IOException { if (contextSize == -1) { contextSize = DEFAULT_CONTEXT_SIZE; } long startTime = System.currentTimeMillis(); List<RuleMatch> ruleMatches = lt.check(contents); // adjust line numbers for (RuleMatch r : ruleMatches) { r.setLine(r.getLine() + lineOffset); r.setEndLine(r.getEndLine() + lineOffset); } if (isXmlFormat) { if (listUnknownWords && apiMode == StringTools.ApiPrintMode.NORMAL_API) { unknownWords = lt.getUnknownWords(); } RuleMatchAsXmlSerializer serializer = new RuleMatchAsXmlSerializer(); String xml = serializer.ruleMatchesToXml(ruleMatches, contents, contextSize, apiMode, lt.getLanguage(), unknownWords); PrintStream out = new PrintStream(System.out, true, "UTF-8"); out.print(xml); } else if (isJsonFormat) { RuleMatchesAsJsonSerializer serializer = new RuleMatchesAsJsonSerializer(); String json = serializer.ruleMatchesToJson(ruleMatches, contents, contextSize, new DetectedLanguage(lt.getLanguage(), lt.getLanguage())); PrintStream out = new PrintStream(System.out, true, "UTF-8"); out.print(json); } else { printMatches(ruleMatches, prevMatches, contents, contextSize); } //display stats if it's not in a buffered mode if (apiMode == StringTools.ApiPrintMode.NORMAL_API && !isJsonFormat) { SentenceTokenizer sentenceTokenizer = lt.getLanguage().getSentenceTokenizer(); int sentenceCount = sentenceTokenizer.tokenize(contents).size(); displayTimeStats(startTime, sentenceCount, isXmlFormat); } return ruleMatches.size(); }
[ "public", "static", "int", "checkText", "(", "String", "contents", ",", "JLanguageTool", "lt", ",", "boolean", "isXmlFormat", ",", "boolean", "isJsonFormat", ",", "int", "contextSize", ",", "int", "lineOffset", ",", "int", "prevMatches", ",", "StringTools", ".", "ApiPrintMode", "apiMode", ",", "boolean", "listUnknownWords", ",", "List", "<", "String", ">", "unknownWords", ")", "throws", "IOException", "{", "if", "(", "contextSize", "==", "-", "1", ")", "{", "contextSize", "=", "DEFAULT_CONTEXT_SIZE", ";", "}", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "List", "<", "RuleMatch", ">", "ruleMatches", "=", "lt", ".", "check", "(", "contents", ")", ";", "// adjust line numbers", "for", "(", "RuleMatch", "r", ":", "ruleMatches", ")", "{", "r", ".", "setLine", "(", "r", ".", "getLine", "(", ")", "+", "lineOffset", ")", ";", "r", ".", "setEndLine", "(", "r", ".", "getEndLine", "(", ")", "+", "lineOffset", ")", ";", "}", "if", "(", "isXmlFormat", ")", "{", "if", "(", "listUnknownWords", "&&", "apiMode", "==", "StringTools", ".", "ApiPrintMode", ".", "NORMAL_API", ")", "{", "unknownWords", "=", "lt", ".", "getUnknownWords", "(", ")", ";", "}", "RuleMatchAsXmlSerializer", "serializer", "=", "new", "RuleMatchAsXmlSerializer", "(", ")", ";", "String", "xml", "=", "serializer", ".", "ruleMatchesToXml", "(", "ruleMatches", ",", "contents", ",", "contextSize", ",", "apiMode", ",", "lt", ".", "getLanguage", "(", ")", ",", "unknownWords", ")", ";", "PrintStream", "out", "=", "new", "PrintStream", "(", "System", ".", "out", ",", "true", ",", "\"UTF-8\"", ")", ";", "out", ".", "print", "(", "xml", ")", ";", "}", "else", "if", "(", "isJsonFormat", ")", "{", "RuleMatchesAsJsonSerializer", "serializer", "=", "new", "RuleMatchesAsJsonSerializer", "(", ")", ";", "String", "json", "=", "serializer", ".", "ruleMatchesToJson", "(", "ruleMatches", ",", "contents", ",", "contextSize", ",", "new", "DetectedLanguage", "(", "lt", ".", "getLanguage", "(", ")", ",", "lt", ".", "getLanguage", "(", ")", ")", ")", ";", "PrintStream", "out", "=", "new", "PrintStream", "(", "System", ".", "out", ",", "true", ",", "\"UTF-8\"", ")", ";", "out", ".", "print", "(", "json", ")", ";", "}", "else", "{", "printMatches", "(", "ruleMatches", ",", "prevMatches", ",", "contents", ",", "contextSize", ")", ";", "}", "//display stats if it's not in a buffered mode", "if", "(", "apiMode", "==", "StringTools", ".", "ApiPrintMode", ".", "NORMAL_API", "&&", "!", "isJsonFormat", ")", "{", "SentenceTokenizer", "sentenceTokenizer", "=", "lt", ".", "getLanguage", "(", ")", ".", "getSentenceTokenizer", "(", ")", ";", "int", "sentenceCount", "=", "sentenceTokenizer", ".", "tokenize", "(", "contents", ")", ".", "size", "(", ")", ";", "displayTimeStats", "(", "startTime", ",", "sentenceCount", ",", "isXmlFormat", ")", ";", "}", "return", "ruleMatches", ".", "size", "(", ")", ";", "}" ]
Check the given text and print results to System.out. @param contents a text to check (may be more than one sentence) @param lt Initialized LanguageTool @param isXmlFormat whether to print the result in XML format @param isJsonFormat whether to print the result in JSON format @param contextSize error text context size: -1 for default @param lineOffset line number offset to be added to line numbers in matches @param prevMatches number of previously matched rules @param apiMode mode of xml/json printout for simple xml/json output @return Number of rule matches to the input text.
[ "Check", "the", "given", "text", "and", "print", "results", "to", "System", ".", "out", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-commandline/src/main/java/org/languagetool/commandline/CommandLineTools.java#L98-L138
19,214
languagetool-org/languagetool
languagetool-commandline/src/main/java/org/languagetool/commandline/CommandLineTools.java
CommandLineTools.printMatches
private static void printMatches(List<RuleMatch> ruleMatches, int prevMatches, String contents, int contextSize) { int i = 1; ContextTools contextTools = new ContextTools(); contextTools.setContextSize(contextSize); for (RuleMatch match : ruleMatches) { Rule rule = match.getRule(); String output = i + prevMatches + ".) Line " + (match.getLine() + 1) + ", column " + match.getColumn() + ", Rule ID: " + rule.getId(); if (rule instanceof AbstractPatternRule) { AbstractPatternRule pRule = (AbstractPatternRule) rule; if (pRule.getSubId() != null) { output += "[" + pRule.getSubId() + "]"; } } System.out.println(output); String msg = match.getMessage(); msg = msg.replaceAll("</?suggestion>", "'"); System.out.println("Message: " + msg); List<String> replacements = match.getSuggestedReplacements(); if (!replacements.isEmpty()) { System.out.println("Suggestion: " + String.join("; ", replacements)); } System.out.println(contextTools.getPlainTextContext(match.getFromPos(), match.getToPos(), contents)); if (match.getUrl() != null) { System.out.println("More info: " + match.getUrl()); } else if (rule.getUrl() != null) { System.out.println("More info: " + rule.getUrl()); } if (i < ruleMatches.size()) { System.out.println(); } i++; } }
java
private static void printMatches(List<RuleMatch> ruleMatches, int prevMatches, String contents, int contextSize) { int i = 1; ContextTools contextTools = new ContextTools(); contextTools.setContextSize(contextSize); for (RuleMatch match : ruleMatches) { Rule rule = match.getRule(); String output = i + prevMatches + ".) Line " + (match.getLine() + 1) + ", column " + match.getColumn() + ", Rule ID: " + rule.getId(); if (rule instanceof AbstractPatternRule) { AbstractPatternRule pRule = (AbstractPatternRule) rule; if (pRule.getSubId() != null) { output += "[" + pRule.getSubId() + "]"; } } System.out.println(output); String msg = match.getMessage(); msg = msg.replaceAll("</?suggestion>", "'"); System.out.println("Message: " + msg); List<String> replacements = match.getSuggestedReplacements(); if (!replacements.isEmpty()) { System.out.println("Suggestion: " + String.join("; ", replacements)); } System.out.println(contextTools.getPlainTextContext(match.getFromPos(), match.getToPos(), contents)); if (match.getUrl() != null) { System.out.println("More info: " + match.getUrl()); } else if (rule.getUrl() != null) { System.out.println("More info: " + rule.getUrl()); } if (i < ruleMatches.size()) { System.out.println(); } i++; } }
[ "private", "static", "void", "printMatches", "(", "List", "<", "RuleMatch", ">", "ruleMatches", ",", "int", "prevMatches", ",", "String", "contents", ",", "int", "contextSize", ")", "{", "int", "i", "=", "1", ";", "ContextTools", "contextTools", "=", "new", "ContextTools", "(", ")", ";", "contextTools", ".", "setContextSize", "(", "contextSize", ")", ";", "for", "(", "RuleMatch", "match", ":", "ruleMatches", ")", "{", "Rule", "rule", "=", "match", ".", "getRule", "(", ")", ";", "String", "output", "=", "i", "+", "prevMatches", "+", "\".) Line \"", "+", "(", "match", ".", "getLine", "(", ")", "+", "1", ")", "+", "\", column \"", "+", "match", ".", "getColumn", "(", ")", "+", "\", Rule ID: \"", "+", "rule", ".", "getId", "(", ")", ";", "if", "(", "rule", "instanceof", "AbstractPatternRule", ")", "{", "AbstractPatternRule", "pRule", "=", "(", "AbstractPatternRule", ")", "rule", ";", "if", "(", "pRule", ".", "getSubId", "(", ")", "!=", "null", ")", "{", "output", "+=", "\"[\"", "+", "pRule", ".", "getSubId", "(", ")", "+", "\"]\"", ";", "}", "}", "System", ".", "out", ".", "println", "(", "output", ")", ";", "String", "msg", "=", "match", ".", "getMessage", "(", ")", ";", "msg", "=", "msg", ".", "replaceAll", "(", "\"</?suggestion>\"", ",", "\"'\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"Message: \"", "+", "msg", ")", ";", "List", "<", "String", ">", "replacements", "=", "match", ".", "getSuggestedReplacements", "(", ")", ";", "if", "(", "!", "replacements", ".", "isEmpty", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"Suggestion: \"", "+", "String", ".", "join", "(", "\"; \"", ",", "replacements", ")", ")", ";", "}", "System", ".", "out", ".", "println", "(", "contextTools", ".", "getPlainTextContext", "(", "match", ".", "getFromPos", "(", ")", ",", "match", ".", "getToPos", "(", ")", ",", "contents", ")", ")", ";", "if", "(", "match", ".", "getUrl", "(", ")", "!=", "null", ")", "{", "System", ".", "out", ".", "println", "(", "\"More info: \"", "+", "match", ".", "getUrl", "(", ")", ")", ";", "}", "else", "if", "(", "rule", ".", "getUrl", "(", ")", "!=", "null", ")", "{", "System", ".", "out", ".", "println", "(", "\"More info: \"", "+", "rule", ".", "getUrl", "(", ")", ")", ";", "}", "if", "(", "i", "<", "ruleMatches", ".", "size", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", ")", ";", "}", "i", "++", ";", "}", "}" ]
Displays matches in a simple text format. @param ruleMatches Matches from rules. @param prevMatches Number of previously found matches. @param contents The text that was checked. @param contextSize The size of contents displayed. @since 1.0.1
[ "Displays", "matches", "in", "a", "simple", "text", "format", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-commandline/src/main/java/org/languagetool/commandline/CommandLineTools.java#L166-L200
19,215
languagetool-org/languagetool
languagetool-commandline/src/main/java/org/languagetool/commandline/CommandLineTools.java
CommandLineTools.profileRulesOnText
public static void profileRulesOnText(String contents, JLanguageTool lt) throws IOException { long[] workTime = new long[10]; List<Rule> rules = lt.getAllActiveRules(); int ruleCount = rules.size(); System.out.printf("Testing %d rules%n", ruleCount); System.out.println("Rule ID\tTime\tSentences\tMatches\tSentences per sec."); List<String> sentences = lt.sentenceTokenize(contents); for (Rule rule : rules) { if (rule instanceof TextLevelRule) { continue; // profile rules for sentences only } int matchCount = 0; for (int k = 0; k < 10; k++) { long startTime = System.currentTimeMillis(); for (String sentence : sentences) { matchCount += rule.match (lt.getAnalyzedSentence(sentence)).length; } long endTime = System.currentTimeMillis(); workTime[k] = endTime - startTime; } long time = median(workTime); float timeInSeconds = time / 1000.0f; float sentencesPerSecond = sentences.size() / timeInSeconds; System.out.printf(Locale.ENGLISH, "%s\t%d\t%d\t%d\t%.1f", rule.getId(), time, sentences.size(), matchCount, sentencesPerSecond); System.out.println(); } }
java
public static void profileRulesOnText(String contents, JLanguageTool lt) throws IOException { long[] workTime = new long[10]; List<Rule> rules = lt.getAllActiveRules(); int ruleCount = rules.size(); System.out.printf("Testing %d rules%n", ruleCount); System.out.println("Rule ID\tTime\tSentences\tMatches\tSentences per sec."); List<String> sentences = lt.sentenceTokenize(contents); for (Rule rule : rules) { if (rule instanceof TextLevelRule) { continue; // profile rules for sentences only } int matchCount = 0; for (int k = 0; k < 10; k++) { long startTime = System.currentTimeMillis(); for (String sentence : sentences) { matchCount += rule.match (lt.getAnalyzedSentence(sentence)).length; } long endTime = System.currentTimeMillis(); workTime[k] = endTime - startTime; } long time = median(workTime); float timeInSeconds = time / 1000.0f; float sentencesPerSecond = sentences.size() / timeInSeconds; System.out.printf(Locale.ENGLISH, "%s\t%d\t%d\t%d\t%.1f", rule.getId(), time, sentences.size(), matchCount, sentencesPerSecond); System.out.println(); } }
[ "public", "static", "void", "profileRulesOnText", "(", "String", "contents", ",", "JLanguageTool", "lt", ")", "throws", "IOException", "{", "long", "[", "]", "workTime", "=", "new", "long", "[", "10", "]", ";", "List", "<", "Rule", ">", "rules", "=", "lt", ".", "getAllActiveRules", "(", ")", ";", "int", "ruleCount", "=", "rules", ".", "size", "(", ")", ";", "System", ".", "out", ".", "printf", "(", "\"Testing %d rules%n\"", ",", "ruleCount", ")", ";", "System", ".", "out", ".", "println", "(", "\"Rule ID\\tTime\\tSentences\\tMatches\\tSentences per sec.\"", ")", ";", "List", "<", "String", ">", "sentences", "=", "lt", ".", "sentenceTokenize", "(", "contents", ")", ";", "for", "(", "Rule", "rule", ":", "rules", ")", "{", "if", "(", "rule", "instanceof", "TextLevelRule", ")", "{", "continue", ";", "// profile rules for sentences only", "}", "int", "matchCount", "=", "0", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "10", ";", "k", "++", ")", "{", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "for", "(", "String", "sentence", ":", "sentences", ")", "{", "matchCount", "+=", "rule", ".", "match", "(", "lt", ".", "getAnalyzedSentence", "(", "sentence", ")", ")", ".", "length", ";", "}", "long", "endTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "workTime", "[", "k", "]", "=", "endTime", "-", "startTime", ";", "}", "long", "time", "=", "median", "(", "workTime", ")", ";", "float", "timeInSeconds", "=", "time", "/", "1000.0f", ";", "float", "sentencesPerSecond", "=", "sentences", ".", "size", "(", ")", "/", "timeInSeconds", ";", "System", ".", "out", ".", "printf", "(", "Locale", ".", "ENGLISH", ",", "\"%s\\t%d\\t%d\\t%d\\t%.1f\"", ",", "rule", ".", "getId", "(", ")", ",", "time", ",", "sentences", ".", "size", "(", ")", ",", "matchCount", ",", "sentencesPerSecond", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "}", "}" ]
Simple rule profiler - used to run LT on a corpus to see which rule takes most time. Prints results to System.out. @param contents text to check @param lt instance of LanguageTool
[ "Simple", "rule", "profiler", "-", "used", "to", "run", "LT", "on", "a", "corpus", "to", "see", "which", "rule", "takes", "most", "time", ".", "Prints", "results", "to", "System", ".", "out", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-commandline/src/main/java/org/languagetool/commandline/CommandLineTools.java#L270-L300
19,216
languagetool-org/languagetool
languagetool-language-modules/nl/src/main/java/org/languagetool/tokenizers/nl/DutchWordTokenizer.java
DutchWordTokenizer.tokenize
@Override public List<String> tokenize(final String text) { final List<String> l = new ArrayList<>(); final StringTokenizer st = new StringTokenizer(text, nlTokenizingChars, true); while (st.hasMoreElements()) { String token = st.nextToken(); String origToken = token; if (token.length() > 1) { if (startsWithQuote(token) && endsWithQuote(token) && token.length() > 2) { l.add(token.substring(0, 1)); l.add(token.substring(1, token.length()-1)); l.add(token.substring(token.length()-1, token.length())); } else if (endsWithQuote(token)) { int cnt = 0; while (endsWithQuote(token)) { token = token.substring(0, token.length() - 1); cnt++; } l.add(token); for (int i = origToken.length() - cnt; i < origToken.length(); i++) { l.add(origToken.substring(i, i + 1)); } } else if (startsWithQuote(token)) { while (startsWithQuote(token)) { l.add(token.substring(0, 1)); token = token.substring(1, token.length()); } l.add(token); } else { l.add(token); } } else { l.add(token); } } return joinEMailsAndUrls(l); }
java
@Override public List<String> tokenize(final String text) { final List<String> l = new ArrayList<>(); final StringTokenizer st = new StringTokenizer(text, nlTokenizingChars, true); while (st.hasMoreElements()) { String token = st.nextToken(); String origToken = token; if (token.length() > 1) { if (startsWithQuote(token) && endsWithQuote(token) && token.length() > 2) { l.add(token.substring(0, 1)); l.add(token.substring(1, token.length()-1)); l.add(token.substring(token.length()-1, token.length())); } else if (endsWithQuote(token)) { int cnt = 0; while (endsWithQuote(token)) { token = token.substring(0, token.length() - 1); cnt++; } l.add(token); for (int i = origToken.length() - cnt; i < origToken.length(); i++) { l.add(origToken.substring(i, i + 1)); } } else if (startsWithQuote(token)) { while (startsWithQuote(token)) { l.add(token.substring(0, 1)); token = token.substring(1, token.length()); } l.add(token); } else { l.add(token); } } else { l.add(token); } } return joinEMailsAndUrls(l); }
[ "@", "Override", "public", "List", "<", "String", ">", "tokenize", "(", "final", "String", "text", ")", "{", "final", "List", "<", "String", ">", "l", "=", "new", "ArrayList", "<>", "(", ")", ";", "final", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "text", ",", "nlTokenizingChars", ",", "true", ")", ";", "while", "(", "st", ".", "hasMoreElements", "(", ")", ")", "{", "String", "token", "=", "st", ".", "nextToken", "(", ")", ";", "String", "origToken", "=", "token", ";", "if", "(", "token", ".", "length", "(", ")", ">", "1", ")", "{", "if", "(", "startsWithQuote", "(", "token", ")", "&&", "endsWithQuote", "(", "token", ")", "&&", "token", ".", "length", "(", ")", ">", "2", ")", "{", "l", ".", "add", "(", "token", ".", "substring", "(", "0", ",", "1", ")", ")", ";", "l", ".", "add", "(", "token", ".", "substring", "(", "1", ",", "token", ".", "length", "(", ")", "-", "1", ")", ")", ";", "l", ".", "add", "(", "token", ".", "substring", "(", "token", ".", "length", "(", ")", "-", "1", ",", "token", ".", "length", "(", ")", ")", ")", ";", "}", "else", "if", "(", "endsWithQuote", "(", "token", ")", ")", "{", "int", "cnt", "=", "0", ";", "while", "(", "endsWithQuote", "(", "token", ")", ")", "{", "token", "=", "token", ".", "substring", "(", "0", ",", "token", ".", "length", "(", ")", "-", "1", ")", ";", "cnt", "++", ";", "}", "l", ".", "add", "(", "token", ")", ";", "for", "(", "int", "i", "=", "origToken", ".", "length", "(", ")", "-", "cnt", ";", "i", "<", "origToken", ".", "length", "(", ")", ";", "i", "++", ")", "{", "l", ".", "add", "(", "origToken", ".", "substring", "(", "i", ",", "i", "+", "1", ")", ")", ";", "}", "}", "else", "if", "(", "startsWithQuote", "(", "token", ")", ")", "{", "while", "(", "startsWithQuote", "(", "token", ")", ")", "{", "l", ".", "add", "(", "token", ".", "substring", "(", "0", ",", "1", ")", ")", ";", "token", "=", "token", ".", "substring", "(", "1", ",", "token", ".", "length", "(", ")", ")", ";", "}", "l", ".", "add", "(", "token", ")", ";", "}", "else", "{", "l", ".", "add", "(", "token", ")", ";", "}", "}", "else", "{", "l", ".", "add", "(", "token", ")", ";", "}", "}", "return", "joinEMailsAndUrls", "(", "l", ")", ";", "}" ]
Tokenizes just like WordTokenizer with the exception for words such as "oma's" that contain an apostrophe in their middle. @param text Text to tokenize @return List of tokens
[ "Tokenizes", "just", "like", "WordTokenizer", "with", "the", "exception", "for", "words", "such", "as", "oma", "s", "that", "contain", "an", "apostrophe", "in", "their", "middle", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-language-modules/nl/src/main/java/org/languagetool/tokenizers/nl/DutchWordTokenizer.java#L51-L87
19,217
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/AnalyzedSentence.java
AnalyzedSentence.getText
public String getText() { StringBuilder sb = new StringBuilder(); for (AnalyzedTokenReadings element : tokens) { sb.append(element.getToken()); } return sb.toString(); }
java
public String getText() { StringBuilder sb = new StringBuilder(); for (AnalyzedTokenReadings element : tokens) { sb.append(element.getToken()); } return sb.toString(); }
[ "public", "String", "getText", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "AnalyzedTokenReadings", "element", ":", "tokens", ")", "{", "sb", ".", "append", "(", "element", ".", "getToken", "(", ")", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Return the original text. @since 2.7
[ "Return", "the", "original", "text", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/AnalyzedSentence.java#L199-L205
19,218
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/AnalyzedSentence.java
AnalyzedSentence.getAnnotations
public String getAnnotations() { StringBuilder sb = new StringBuilder(40); sb.append("Disambiguator log: \n"); for (AnalyzedTokenReadings element : tokens) { if (!element.isWhitespace() && !"".equals(element.getHistoricalAnnotations())) { sb.append(element.getHistoricalAnnotations()); sb.append('\n'); } } return sb.toString(); }
java
public String getAnnotations() { StringBuilder sb = new StringBuilder(40); sb.append("Disambiguator log: \n"); for (AnalyzedTokenReadings element : tokens) { if (!element.isWhitespace() && !"".equals(element.getHistoricalAnnotations())) { sb.append(element.getHistoricalAnnotations()); sb.append('\n'); } } return sb.toString(); }
[ "public", "String", "getAnnotations", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "40", ")", ";", "sb", ".", "append", "(", "\"Disambiguator log: \\n\"", ")", ";", "for", "(", "AnalyzedTokenReadings", "element", ":", "tokens", ")", "{", "if", "(", "!", "element", ".", "isWhitespace", "(", ")", "&&", "!", "\"\"", ".", "equals", "(", "element", ".", "getHistoricalAnnotations", "(", ")", ")", ")", "{", "sb", ".", "append", "(", "element", ".", "getHistoricalAnnotations", "(", ")", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Get disambiguator actions log.
[ "Get", "disambiguator", "actions", "log", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/AnalyzedSentence.java#L270-L281
19,219
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/tools/StringTools.java
StringTools.assureSet
public static void assureSet(String s, String varName) { Objects.requireNonNull(varName); if (isEmpty(s.trim())) { throw new IllegalArgumentException(varName + " cannot be empty or whitespace only"); } }
java
public static void assureSet(String s, String varName) { Objects.requireNonNull(varName); if (isEmpty(s.trim())) { throw new IllegalArgumentException(varName + " cannot be empty or whitespace only"); } }
[ "public", "static", "void", "assureSet", "(", "String", "s", ",", "String", "varName", ")", "{", "Objects", ".", "requireNonNull", "(", "varName", ")", ";", "if", "(", "isEmpty", "(", "s", ".", "trim", "(", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "varName", "+", "\" cannot be empty or whitespace only\"", ")", ";", "}", "}" ]
Throw exception if the given string is null or empty or only whitespace.
[ "Throw", "exception", "if", "the", "given", "string", "is", "null", "or", "empty", "or", "only", "whitespace", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/tools/StringTools.java#L82-L87
19,220
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/tools/StringTools.java
StringTools.readStream
public static String readStream(InputStream stream, String encoding) throws IOException { InputStreamReader isr = null; StringBuilder sb = new StringBuilder(); try { if (encoding == null) { isr = new InputStreamReader(stream); } else { isr = new InputStreamReader(stream, encoding); } try (BufferedReader br = new BufferedReader(isr)) { String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append('\n'); } } } finally { if (isr != null) { isr.close(); } } return sb.toString(); }
java
public static String readStream(InputStream stream, String encoding) throws IOException { InputStreamReader isr = null; StringBuilder sb = new StringBuilder(); try { if (encoding == null) { isr = new InputStreamReader(stream); } else { isr = new InputStreamReader(stream, encoding); } try (BufferedReader br = new BufferedReader(isr)) { String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append('\n'); } } } finally { if (isr != null) { isr.close(); } } return sb.toString(); }
[ "public", "static", "String", "readStream", "(", "InputStream", "stream", ",", "String", "encoding", ")", "throws", "IOException", "{", "InputStreamReader", "isr", "=", "null", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "try", "{", "if", "(", "encoding", "==", "null", ")", "{", "isr", "=", "new", "InputStreamReader", "(", "stream", ")", ";", "}", "else", "{", "isr", "=", "new", "InputStreamReader", "(", "stream", ",", "encoding", ")", ";", "}", "try", "(", "BufferedReader", "br", "=", "new", "BufferedReader", "(", "isr", ")", ")", "{", "String", "line", ";", "while", "(", "(", "line", "=", "br", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "sb", ".", "append", "(", "line", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "}", "}", "finally", "{", "if", "(", "isr", "!=", "null", ")", "{", "isr", ".", "close", "(", ")", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Read the text stream using the given encoding. @param stream InputStream the stream to be read @param encoding the stream's character encoding, e.g. {@code utf-8}, or {@code null} to use the system encoding @return a string with the stream's content, lines separated by {@code \n} (note that {@code \n} will be added to the last line even if it is not in the stream) @since 2.3
[ "Read", "the", "text", "stream", "using", "the", "given", "encoding", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/tools/StringTools.java#L98-L120
19,221
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/tools/StringTools.java
StringTools.addSpace
public static String addSpace(String word, Language language) { String space = " "; if (word.length() == 1) { char c = word.charAt(0); if ("fr".equals(language.getShortCode())) { if (c == '.' || c == ',') { space = ""; } } else { if (c == '.' || c == ',' || c == ';' || c == ':' || c == '?' || c == '!') { space = ""; } } } return space; }
java
public static String addSpace(String word, Language language) { String space = " "; if (word.length() == 1) { char c = word.charAt(0); if ("fr".equals(language.getShortCode())) { if (c == '.' || c == ',') { space = ""; } } else { if (c == '.' || c == ',' || c == ';' || c == ':' || c == '?' || c == '!') { space = ""; } } } return space; }
[ "public", "static", "String", "addSpace", "(", "String", "word", ",", "Language", "language", ")", "{", "String", "space", "=", "\" \"", ";", "if", "(", "word", ".", "length", "(", ")", "==", "1", ")", "{", "char", "c", "=", "word", ".", "charAt", "(", "0", ")", ";", "if", "(", "\"fr\"", ".", "equals", "(", "language", ".", "getShortCode", "(", ")", ")", ")", "{", "if", "(", "c", "==", "'", "'", "||", "c", "==", "'", "'", ")", "{", "space", "=", "\"\"", ";", "}", "}", "else", "{", "if", "(", "c", "==", "'", "'", "||", "c", "==", "'", "'", "||", "c", "==", "'", "'", "||", "c", "==", "'", "'", "||", "c", "==", "'", "'", "||", "c", "==", "'", "'", ")", "{", "space", "=", "\"\"", ";", "}", "}", "}", "return", "space", ";", "}" ]
Adds spaces before words that are not punctuation. @param word Word to add the preceding space. @param language Language of the word (to check typography conventions). Currently French convention of not adding spaces only before '.' and ',' is implemented; other languages assume that before ,.;:!? no spaces should be added. @return String containing a space or an empty string.
[ "Adds", "spaces", "before", "words", "that", "are", "not", "punctuation", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/tools/StringTools.java#L372-L387
19,222
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/tools/StringTools.java
StringTools.filterXML
public static String filterXML(String str) { String s = str; if (s.contains("<")) { // don't run slow regex unless we have to s = XML_COMMENT_PATTERN.matcher(s).replaceAll(" "); s = XML_PATTERN.matcher(s).replaceAll(""); } return s; }
java
public static String filterXML(String str) { String s = str; if (s.contains("<")) { // don't run slow regex unless we have to s = XML_COMMENT_PATTERN.matcher(s).replaceAll(" "); s = XML_PATTERN.matcher(s).replaceAll(""); } return s; }
[ "public", "static", "String", "filterXML", "(", "String", "str", ")", "{", "String", "s", "=", "str", ";", "if", "(", "s", ".", "contains", "(", "\"<\"", ")", ")", "{", "// don't run slow regex unless we have to", "s", "=", "XML_COMMENT_PATTERN", ".", "matcher", "(", "s", ")", ".", "replaceAll", "(", "\" \"", ")", ";", "s", "=", "XML_PATTERN", ".", "matcher", "(", "s", ")", ".", "replaceAll", "(", "\"\"", ")", ";", "}", "return", "s", ";", "}" ]
Simple XML filtering for XML tags. @param str XML string to be filtered. @return Filtered string without XML tags.
[ "Simple", "XML", "filtering", "for", "XML", "tags", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/tools/StringTools.java#L452-L459
19,223
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/Language.java
Language.getTranslatedName
public final String getTranslatedName(ResourceBundle messages) { try { return messages.getString(getShortCodeWithCountryAndVariant()); } catch (MissingResourceException e) { try { return messages.getString(getShortCode()); } catch (MissingResourceException e1) { return getName(); } } }
java
public final String getTranslatedName(ResourceBundle messages) { try { return messages.getString(getShortCodeWithCountryAndVariant()); } catch (MissingResourceException e) { try { return messages.getString(getShortCode()); } catch (MissingResourceException e1) { return getName(); } } }
[ "public", "final", "String", "getTranslatedName", "(", "ResourceBundle", "messages", ")", "{", "try", "{", "return", "messages", ".", "getString", "(", "getShortCodeWithCountryAndVariant", "(", ")", ")", ";", "}", "catch", "(", "MissingResourceException", "e", ")", "{", "try", "{", "return", "messages", ".", "getString", "(", "getShortCode", "(", ")", ")", ";", "}", "catch", "(", "MissingResourceException", "e1", ")", "{", "return", "getName", "(", ")", ";", "}", "}", "}" ]
Get the name of the language translated to the current locale, if available. Otherwise, get the untranslated name.
[ "Get", "the", "name", "of", "the", "language", "translated", "to", "the", "current", "locale", "if", "available", ".", "Otherwise", "get", "the", "untranslated", "name", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/Language.java#L349-L359
19,224
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/ResultCache.java
ResultCache.remove
void remove(int numberOfParagraph, int startOfSentencePosition) { for(int i = 0; i < entries.size(); i++) { if(entries.get(i).numberOfParagraph == numberOfParagraph && entries.get(i).startOfSentencePosition == startOfSentencePosition) { entries.remove(i); return; } } }
java
void remove(int numberOfParagraph, int startOfSentencePosition) { for(int i = 0; i < entries.size(); i++) { if(entries.get(i).numberOfParagraph == numberOfParagraph && entries.get(i).startOfSentencePosition == startOfSentencePosition) { entries.remove(i); return; } } }
[ "void", "remove", "(", "int", "numberOfParagraph", ",", "int", "startOfSentencePosition", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "entries", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "entries", ".", "get", "(", "i", ")", ".", "numberOfParagraph", "==", "numberOfParagraph", "&&", "entries", ".", "get", "(", "i", ")", ".", "startOfSentencePosition", "==", "startOfSentencePosition", ")", "{", "entries", ".", "remove", "(", "i", ")", ";", "return", ";", "}", "}", "}" ]
Remove a cache entry for a sentence
[ "Remove", "a", "cache", "entry", "for", "a", "sentence" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/ResultCache.java#L42-L50
19,225
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/ResultCache.java
ResultCache.removeRange
void removeRange(int firstParagraph, int lastParagraph) { for(int i = 0; i < entries.size(); i++) { if(entries.get(i).numberOfParagraph >= firstParagraph && entries.get(i).numberOfParagraph <= lastParagraph) { entries.remove(i); i--; } } }
java
void removeRange(int firstParagraph, int lastParagraph) { for(int i = 0; i < entries.size(); i++) { if(entries.get(i).numberOfParagraph >= firstParagraph && entries.get(i).numberOfParagraph <= lastParagraph) { entries.remove(i); i--; } } }
[ "void", "removeRange", "(", "int", "firstParagraph", ",", "int", "lastParagraph", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "entries", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "entries", ".", "get", "(", "i", ")", ".", "numberOfParagraph", ">=", "firstParagraph", "&&", "entries", ".", "get", "(", "i", ")", ".", "numberOfParagraph", "<=", "lastParagraph", ")", "{", "entries", ".", "remove", "(", "i", ")", ";", "i", "--", ";", "}", "}", "}" ]
Remove all cache entries between firstParagraph and lastParagraph
[ "Remove", "all", "cache", "entries", "between", "firstParagraph", "and", "lastParagraph" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/ResultCache.java#L67-L74
19,226
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/ResultCache.java
ResultCache.add
public void add(int numberOfParagraph, int startOfSentencePosition, int nextSentencePosition, SingleProofreadingError[] errorArray) { entries.add(new CacheEntry(numberOfParagraph, startOfSentencePosition, nextSentencePosition, errorArray)); }
java
public void add(int numberOfParagraph, int startOfSentencePosition, int nextSentencePosition, SingleProofreadingError[] errorArray) { entries.add(new CacheEntry(numberOfParagraph, startOfSentencePosition, nextSentencePosition, errorArray)); }
[ "public", "void", "add", "(", "int", "numberOfParagraph", ",", "int", "startOfSentencePosition", ",", "int", "nextSentencePosition", ",", "SingleProofreadingError", "[", "]", "errorArray", ")", "{", "entries", ".", "add", "(", "new", "CacheEntry", "(", "numberOfParagraph", ",", "startOfSentencePosition", ",", "nextSentencePosition", ",", "errorArray", ")", ")", ";", "}" ]
Add an cache entry
[ "Add", "an", "cache", "entry" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/ResultCache.java#L97-L99
19,227
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/ResultCache.java
ResultCache.put
void put(int numberOfParagraph, int startOfSentencePosition, int nextSentencePosition, SingleProofreadingError[] errorArray) { remove(numberOfParagraph, startOfSentencePosition); add(numberOfParagraph, startOfSentencePosition, nextSentencePosition, errorArray); }
java
void put(int numberOfParagraph, int startOfSentencePosition, int nextSentencePosition, SingleProofreadingError[] errorArray) { remove(numberOfParagraph, startOfSentencePosition); add(numberOfParagraph, startOfSentencePosition, nextSentencePosition, errorArray); }
[ "void", "put", "(", "int", "numberOfParagraph", ",", "int", "startOfSentencePosition", ",", "int", "nextSentencePosition", ",", "SingleProofreadingError", "[", "]", "errorArray", ")", "{", "remove", "(", "numberOfParagraph", ",", "startOfSentencePosition", ")", ";", "add", "(", "numberOfParagraph", ",", "startOfSentencePosition", ",", "nextSentencePosition", ",", "errorArray", ")", ";", "}" ]
replace an cache entry
[ "replace", "an", "cache", "entry" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/ResultCache.java#L111-L114
19,228
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/ResultCache.java
ResultCache.getFromPara
SingleProofreadingError[] getFromPara(int numberOfParagraph, int startOfSentencePosition, int endOfSentencePosition) { for (CacheEntry anEntry : entries) { if (anEntry.numberOfParagraph == numberOfParagraph) { List<SingleProofreadingError> errorList = new ArrayList<>(); for (SingleProofreadingError eArray : anEntry.errorArray) { if (eArray.nErrorStart >= startOfSentencePosition && eArray.nErrorStart < endOfSentencePosition) { errorList.add(eArray); } } return errorList.toArray(new SingleProofreadingError[0]); } } return null; }
java
SingleProofreadingError[] getFromPara(int numberOfParagraph, int startOfSentencePosition, int endOfSentencePosition) { for (CacheEntry anEntry : entries) { if (anEntry.numberOfParagraph == numberOfParagraph) { List<SingleProofreadingError> errorList = new ArrayList<>(); for (SingleProofreadingError eArray : anEntry.errorArray) { if (eArray.nErrorStart >= startOfSentencePosition && eArray.nErrorStart < endOfSentencePosition) { errorList.add(eArray); } } return errorList.toArray(new SingleProofreadingError[0]); } } return null; }
[ "SingleProofreadingError", "[", "]", "getFromPara", "(", "int", "numberOfParagraph", ",", "int", "startOfSentencePosition", ",", "int", "endOfSentencePosition", ")", "{", "for", "(", "CacheEntry", "anEntry", ":", "entries", ")", "{", "if", "(", "anEntry", ".", "numberOfParagraph", "==", "numberOfParagraph", ")", "{", "List", "<", "SingleProofreadingError", ">", "errorList", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "SingleProofreadingError", "eArray", ":", "anEntry", ".", "errorArray", ")", "{", "if", "(", "eArray", ".", "nErrorStart", ">=", "startOfSentencePosition", "&&", "eArray", ".", "nErrorStart", "<", "endOfSentencePosition", ")", "{", "errorList", ".", "add", "(", "eArray", ")", ";", "}", "}", "return", "errorList", ".", "toArray", "(", "new", "SingleProofreadingError", "[", "0", "]", ")", ";", "}", "}", "return", "null", ";", "}" ]
get Proofreading errors of sentence out of paragraph matches from cache
[ "get", "Proofreading", "errors", "of", "sentence", "out", "of", "paragraph", "matches", "from", "cache" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/ResultCache.java#L157-L171
19,229
languagetool-org/languagetool
languagetool-language-modules/en/src/main/java/org/languagetool/chunking/EnglishChunkFilter.java
EnglishChunkFilter.getChunkType
private ChunkType getChunkType(List<ChunkTaggedToken> tokens, int chunkStartPos) { boolean isPlural = false; for (int i = chunkStartPos; i < tokens.size(); i++) { ChunkTaggedToken token = tokens.get(i); if (!isBeginningOfNounPhrase(token) && !isContinuationOfNounPhrase(token)) { break; } if (false && "and".equals(token.getToken())) { // e.g. "Tarzan and Jane" is a plural noun phrase // TODO: "Additionally, there are over 500 college and university chapter." isPlural = true; } else if (hasNounWithPluralReading(token)) { // e.g. "ten books" is a plural noun phrase isPlural = true; } } return isPlural ? ChunkType.PLURAL : ChunkType.SINGULAR; }
java
private ChunkType getChunkType(List<ChunkTaggedToken> tokens, int chunkStartPos) { boolean isPlural = false; for (int i = chunkStartPos; i < tokens.size(); i++) { ChunkTaggedToken token = tokens.get(i); if (!isBeginningOfNounPhrase(token) && !isContinuationOfNounPhrase(token)) { break; } if (false && "and".equals(token.getToken())) { // e.g. "Tarzan and Jane" is a plural noun phrase // TODO: "Additionally, there are over 500 college and university chapter." isPlural = true; } else if (hasNounWithPluralReading(token)) { // e.g. "ten books" is a plural noun phrase isPlural = true; } } return isPlural ? ChunkType.PLURAL : ChunkType.SINGULAR; }
[ "private", "ChunkType", "getChunkType", "(", "List", "<", "ChunkTaggedToken", ">", "tokens", ",", "int", "chunkStartPos", ")", "{", "boolean", "isPlural", "=", "false", ";", "for", "(", "int", "i", "=", "chunkStartPos", ";", "i", "<", "tokens", ".", "size", "(", ")", ";", "i", "++", ")", "{", "ChunkTaggedToken", "token", "=", "tokens", ".", "get", "(", "i", ")", ";", "if", "(", "!", "isBeginningOfNounPhrase", "(", "token", ")", "&&", "!", "isContinuationOfNounPhrase", "(", "token", ")", ")", "{", "break", ";", "}", "if", "(", "false", "&&", "\"and\"", ".", "equals", "(", "token", ".", "getToken", "(", ")", ")", ")", "{", "// e.g. \"Tarzan and Jane\" is a plural noun phrase", "// TODO: \"Additionally, there are over 500 college and university chapter.\"", "isPlural", "=", "true", ";", "}", "else", "if", "(", "hasNounWithPluralReading", "(", "token", ")", ")", "{", "// e.g. \"ten books\" is a plural noun phrase", "isPlural", "=", "true", ";", "}", "}", "return", "isPlural", "?", "ChunkType", ".", "PLURAL", ":", "ChunkType", ".", "SINGULAR", ";", "}" ]
Get the type of the chunk that starts at the given position.
[ "Get", "the", "type", "of", "the", "chunk", "that", "starts", "at", "the", "given", "position", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-language-modules/en/src/main/java/org/languagetool/chunking/EnglishChunkFilter.java#L94-L109
19,230
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/patterns/PatternTokenMatcher.java
PatternTokenMatcher.addMemberAndGroup
public final void addMemberAndGroup(AnalyzedToken token) { if (patternToken.hasAndGroup()) { List<PatternTokenMatcher> andGroupList = andGroup; for (int i = 0; i < andGroupList.size(); i++) { if (!andGroupCheck[i + 1]) { PatternTokenMatcher testAndGroup = andGroupList.get(i); if (testAndGroup.isMatched(token)) { andGroupCheck[i + 1] = true; } } } } }
java
public final void addMemberAndGroup(AnalyzedToken token) { if (patternToken.hasAndGroup()) { List<PatternTokenMatcher> andGroupList = andGroup; for (int i = 0; i < andGroupList.size(); i++) { if (!andGroupCheck[i + 1]) { PatternTokenMatcher testAndGroup = andGroupList.get(i); if (testAndGroup.isMatched(token)) { andGroupCheck[i + 1] = true; } } } } }
[ "public", "final", "void", "addMemberAndGroup", "(", "AnalyzedToken", "token", ")", "{", "if", "(", "patternToken", ".", "hasAndGroup", "(", ")", ")", "{", "List", "<", "PatternTokenMatcher", ">", "andGroupList", "=", "andGroup", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "andGroupList", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "!", "andGroupCheck", "[", "i", "+", "1", "]", ")", "{", "PatternTokenMatcher", "testAndGroup", "=", "andGroupList", ".", "get", "(", "i", ")", ";", "if", "(", "testAndGroup", ".", "isMatched", "(", "token", ")", ")", "{", "andGroupCheck", "[", "i", "+", "1", "]", "=", "true", ";", "}", "}", "}", "}", "}" ]
Enables testing multiple conditions specified by different elements. Doesn't test exceptions. Works as logical AND operator only if preceded with {@link #prepareAndGroup(int, AnalyzedTokenReadings[], Language)}, and followed by {@link #checkAndGroup(boolean)} @param token the token checked.
[ "Enables", "testing", "multiple", "conditions", "specified", "by", "different", "elements", ".", "Doesn", "t", "test", "exceptions", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/patterns/PatternTokenMatcher.java#L102-L114
19,231
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/patterns/PatternRuleXmlCreator.java
PatternRuleXmlCreator.toXML
public final String toXML(PatternRuleId ruleId, Language language) { List<String> filenames = language.getRuleFileNames(); XPath xpath = XPathFactory.newInstance().newXPath(); for (String filename : filenames) { try (InputStream is = this.getClass().getResourceAsStream(filename)) { Document doc = getDocument(is); Node ruleNode = (Node) xpath.evaluate("/rules/category/rule[@id='" + ruleId.getId() + "']", doc, XPathConstants.NODE); if (ruleNode != null) { return nodeToString(ruleNode); } Node ruleNodeInGroup = (Node) xpath.evaluate("/rules/category/rulegroup/rule[@id='" + ruleId.getId() + "']", doc, XPathConstants.NODE); if (ruleNodeInGroup != null) { return nodeToString(ruleNodeInGroup); } if (ruleId.getSubId() != null) { NodeList ruleGroupNodes = (NodeList) xpath.evaluate("/rules/category/rulegroup[@id='" + ruleId.getId() + "']/rule", doc, XPathConstants.NODESET); if (ruleGroupNodes != null) { for (int i = 0; i < ruleGroupNodes.getLength(); i++) { if (Integer.toString(i+1).equals(ruleId.getSubId())) { return nodeToString(ruleGroupNodes.item(i)); } } } } else { Node ruleGroupNode = (Node) xpath.evaluate("/rules/category/rulegroup[@id='" + ruleId.getId() + "']", doc, XPathConstants.NODE); if (ruleGroupNode != null) { return nodeToString(ruleGroupNode); } } } catch (Exception e) { throw new RuntimeException("Could not turn rule '" + ruleId + "' for language " + language + " into a string", e); } } throw new RuntimeException("Could not find rule '" + ruleId + "' for language " + language + " in files: " + filenames); }
java
public final String toXML(PatternRuleId ruleId, Language language) { List<String> filenames = language.getRuleFileNames(); XPath xpath = XPathFactory.newInstance().newXPath(); for (String filename : filenames) { try (InputStream is = this.getClass().getResourceAsStream(filename)) { Document doc = getDocument(is); Node ruleNode = (Node) xpath.evaluate("/rules/category/rule[@id='" + ruleId.getId() + "']", doc, XPathConstants.NODE); if (ruleNode != null) { return nodeToString(ruleNode); } Node ruleNodeInGroup = (Node) xpath.evaluate("/rules/category/rulegroup/rule[@id='" + ruleId.getId() + "']", doc, XPathConstants.NODE); if (ruleNodeInGroup != null) { return nodeToString(ruleNodeInGroup); } if (ruleId.getSubId() != null) { NodeList ruleGroupNodes = (NodeList) xpath.evaluate("/rules/category/rulegroup[@id='" + ruleId.getId() + "']/rule", doc, XPathConstants.NODESET); if (ruleGroupNodes != null) { for (int i = 0; i < ruleGroupNodes.getLength(); i++) { if (Integer.toString(i+1).equals(ruleId.getSubId())) { return nodeToString(ruleGroupNodes.item(i)); } } } } else { Node ruleGroupNode = (Node) xpath.evaluate("/rules/category/rulegroup[@id='" + ruleId.getId() + "']", doc, XPathConstants.NODE); if (ruleGroupNode != null) { return nodeToString(ruleGroupNode); } } } catch (Exception e) { throw new RuntimeException("Could not turn rule '" + ruleId + "' for language " + language + " into a string", e); } } throw new RuntimeException("Could not find rule '" + ruleId + "' for language " + language + " in files: " + filenames); }
[ "public", "final", "String", "toXML", "(", "PatternRuleId", "ruleId", ",", "Language", "language", ")", "{", "List", "<", "String", ">", "filenames", "=", "language", ".", "getRuleFileNames", "(", ")", ";", "XPath", "xpath", "=", "XPathFactory", ".", "newInstance", "(", ")", ".", "newXPath", "(", ")", ";", "for", "(", "String", "filename", ":", "filenames", ")", "{", "try", "(", "InputStream", "is", "=", "this", ".", "getClass", "(", ")", ".", "getResourceAsStream", "(", "filename", ")", ")", "{", "Document", "doc", "=", "getDocument", "(", "is", ")", ";", "Node", "ruleNode", "=", "(", "Node", ")", "xpath", ".", "evaluate", "(", "\"/rules/category/rule[@id='\"", "+", "ruleId", ".", "getId", "(", ")", "+", "\"']\"", ",", "doc", ",", "XPathConstants", ".", "NODE", ")", ";", "if", "(", "ruleNode", "!=", "null", ")", "{", "return", "nodeToString", "(", "ruleNode", ")", ";", "}", "Node", "ruleNodeInGroup", "=", "(", "Node", ")", "xpath", ".", "evaluate", "(", "\"/rules/category/rulegroup/rule[@id='\"", "+", "ruleId", ".", "getId", "(", ")", "+", "\"']\"", ",", "doc", ",", "XPathConstants", ".", "NODE", ")", ";", "if", "(", "ruleNodeInGroup", "!=", "null", ")", "{", "return", "nodeToString", "(", "ruleNodeInGroup", ")", ";", "}", "if", "(", "ruleId", ".", "getSubId", "(", ")", "!=", "null", ")", "{", "NodeList", "ruleGroupNodes", "=", "(", "NodeList", ")", "xpath", ".", "evaluate", "(", "\"/rules/category/rulegroup[@id='\"", "+", "ruleId", ".", "getId", "(", ")", "+", "\"']/rule\"", ",", "doc", ",", "XPathConstants", ".", "NODESET", ")", ";", "if", "(", "ruleGroupNodes", "!=", "null", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ruleGroupNodes", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "if", "(", "Integer", ".", "toString", "(", "i", "+", "1", ")", ".", "equals", "(", "ruleId", ".", "getSubId", "(", ")", ")", ")", "{", "return", "nodeToString", "(", "ruleGroupNodes", ".", "item", "(", "i", ")", ")", ";", "}", "}", "}", "}", "else", "{", "Node", "ruleGroupNode", "=", "(", "Node", ")", "xpath", ".", "evaluate", "(", "\"/rules/category/rulegroup[@id='\"", "+", "ruleId", ".", "getId", "(", ")", "+", "\"']\"", ",", "doc", ",", "XPathConstants", ".", "NODE", ")", ";", "if", "(", "ruleGroupNode", "!=", "null", ")", "{", "return", "nodeToString", "(", "ruleGroupNode", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not turn rule '\"", "+", "ruleId", "+", "\"' for language \"", "+", "language", "+", "\" into a string\"", ",", "e", ")", ";", "}", "}", "throw", "new", "RuntimeException", "(", "\"Could not find rule '\"", "+", "ruleId", "+", "\"' for language \"", "+", "language", "+", "\" in files: \"", "+", "filenames", ")", ";", "}" ]
Return the given pattern rule as an indented XML string. @since 2.3
[ "Return", "the", "given", "pattern", "rule", "as", "an", "indented", "XML", "string", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/patterns/PatternRuleXmlCreator.java#L55-L89
19,232
languagetool-org/languagetool
languagetool-language-modules/pl/src/main/java/org/languagetool/rules/pl/MorfologikPolishSpellerRule.java
MorfologikPolishSpellerRule.isNotCompound
private boolean isNotCompound(String word) throws IOException { List<String> probablyCorrectWords = new ArrayList<>(); List<String> testedTokens = new ArrayList<>(2); for (int i = 2; i < word.length(); i++) { // chop from left to right final String first = word.substring(0, i); final String second = word.substring(i, word.length()); if (prefixes.contains(first.toLowerCase(conversionLocale)) && !isMisspelled(speller1, second) && second.length() > first.length()) { // but not for short words such as "premoc" // ignore this match, it's fine probablyCorrectWords.add(word); // FIXME: some strange words are being accepted, like prekupa } else { testedTokens.clear(); testedTokens.add(first); testedTokens.add(second); List<AnalyzedTokenReadings> taggedToks = language.getTagger().tag(testedTokens); if (taggedToks.size() == 2 // "białozielony", trzynastobitowy && (taggedToks.get(0).hasPosTag("adja") || (taggedToks.get(0).hasPosTag("num:comp") && !taggedToks.get(0).hasPosTag("adv"))) && taggedToks.get(1).hasPartialPosTag("adj:")) { probablyCorrectWords.add(word); } } } if (!probablyCorrectWords.isEmpty()) { addIgnoreTokens(probablyCorrectWords); return false; } return true; }
java
private boolean isNotCompound(String word) throws IOException { List<String> probablyCorrectWords = new ArrayList<>(); List<String> testedTokens = new ArrayList<>(2); for (int i = 2; i < word.length(); i++) { // chop from left to right final String first = word.substring(0, i); final String second = word.substring(i, word.length()); if (prefixes.contains(first.toLowerCase(conversionLocale)) && !isMisspelled(speller1, second) && second.length() > first.length()) { // but not for short words such as "premoc" // ignore this match, it's fine probablyCorrectWords.add(word); // FIXME: some strange words are being accepted, like prekupa } else { testedTokens.clear(); testedTokens.add(first); testedTokens.add(second); List<AnalyzedTokenReadings> taggedToks = language.getTagger().tag(testedTokens); if (taggedToks.size() == 2 // "białozielony", trzynastobitowy && (taggedToks.get(0).hasPosTag("adja") || (taggedToks.get(0).hasPosTag("num:comp") && !taggedToks.get(0).hasPosTag("adv"))) && taggedToks.get(1).hasPartialPosTag("adj:")) { probablyCorrectWords.add(word); } } } if (!probablyCorrectWords.isEmpty()) { addIgnoreTokens(probablyCorrectWords); return false; } return true; }
[ "private", "boolean", "isNotCompound", "(", "String", "word", ")", "throws", "IOException", "{", "List", "<", "String", ">", "probablyCorrectWords", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "String", ">", "testedTokens", "=", "new", "ArrayList", "<>", "(", "2", ")", ";", "for", "(", "int", "i", "=", "2", ";", "i", "<", "word", ".", "length", "(", ")", ";", "i", "++", ")", "{", "// chop from left to right", "final", "String", "first", "=", "word", ".", "substring", "(", "0", ",", "i", ")", ";", "final", "String", "second", "=", "word", ".", "substring", "(", "i", ",", "word", ".", "length", "(", ")", ")", ";", "if", "(", "prefixes", ".", "contains", "(", "first", ".", "toLowerCase", "(", "conversionLocale", ")", ")", "&&", "!", "isMisspelled", "(", "speller1", ",", "second", ")", "&&", "second", ".", "length", "(", ")", ">", "first", ".", "length", "(", ")", ")", "{", "// but not for short words such as \"premoc\"", "// ignore this match, it's fine", "probablyCorrectWords", ".", "add", "(", "word", ")", ";", "// FIXME: some strange words are being accepted, like prekupa", "}", "else", "{", "testedTokens", ".", "clear", "(", ")", ";", "testedTokens", ".", "add", "(", "first", ")", ";", "testedTokens", ".", "add", "(", "second", ")", ";", "List", "<", "AnalyzedTokenReadings", ">", "taggedToks", "=", "language", ".", "getTagger", "(", ")", ".", "tag", "(", "testedTokens", ")", ";", "if", "(", "taggedToks", ".", "size", "(", ")", "==", "2", "// \"białozielony\", trzynastobitowy", "&&", "(", "taggedToks", ".", "get", "(", "0", ")", ".", "hasPosTag", "(", "\"adja\"", ")", "||", "(", "taggedToks", ".", "get", "(", "0", ")", ".", "hasPosTag", "(", "\"num:comp\"", ")", "&&", "!", "taggedToks", ".", "get", "(", "0", ")", ".", "hasPosTag", "(", "\"adv\"", ")", ")", ")", "&&", "taggedToks", ".", "get", "(", "1", ")", ".", "hasPartialPosTag", "(", "\"adj:\"", ")", ")", "{", "probablyCorrectWords", ".", "add", "(", "word", ")", ";", "}", "}", "}", "if", "(", "!", "probablyCorrectWords", ".", "isEmpty", "(", ")", ")", "{", "addIgnoreTokens", "(", "probablyCorrectWords", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check whether the word is a compound adjective or contains a non-splitting prefix. Used to suppress false positives. @param word Word to be checked. @return True if the word is not a compound. @since 2.5
[ "Check", "whether", "the", "word", "is", "a", "compound", "adjective", "or", "contains", "a", "non", "-", "splitting", "prefix", ".", "Used", "to", "suppress", "false", "positives", "." ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-language-modules/pl/src/main/java/org/languagetool/rules/pl/MorfologikPolishSpellerRule.java#L159-L192
19,233
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/MessageHandler.java
MessageHandler.initLogFile
private static void initLogFile() { try (BufferedWriter bw = new BufferedWriter(new FileWriter(getLogPath()))) { Date date = new Date(); bw.write("LT office integration log from " + date.toString() + logLineBreak); } catch (Throwable t) { showError(t); } }
java
private static void initLogFile() { try (BufferedWriter bw = new BufferedWriter(new FileWriter(getLogPath()))) { Date date = new Date(); bw.write("LT office integration log from " + date.toString() + logLineBreak); } catch (Throwable t) { showError(t); } }
[ "private", "static", "void", "initLogFile", "(", ")", "{", "try", "(", "BufferedWriter", "bw", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "getLogPath", "(", ")", ")", ")", ")", "{", "Date", "date", "=", "new", "Date", "(", ")", ";", "bw", ".", "write", "(", "\"LT office integration log from \"", "+", "date", ".", "toString", "(", ")", "+", "logLineBreak", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "showError", "(", "t", ")", ";", "}", "}" ]
Initialize log-file
[ "Initialize", "log", "-", "file" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/MessageHandler.java#L54-L61
19,234
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/MessageHandler.java
MessageHandler.printToLogFile
static void printToLogFile(String str) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(getLogPath(), true))) { bw.write(str + logLineBreak); } catch (Throwable t) { showError(t); } }
java
static void printToLogFile(String str) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(getLogPath(), true))) { bw.write(str + logLineBreak); } catch (Throwable t) { showError(t); } }
[ "static", "void", "printToLogFile", "(", "String", "str", ")", "{", "try", "(", "BufferedWriter", "bw", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "getLogPath", "(", ")", ",", "true", ")", ")", ")", "{", "bw", ".", "write", "(", "str", "+", "logLineBreak", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "showError", "(", "t", ")", ";", "}", "}" ]
write to log-file
[ "write", "to", "log", "-", "file" ]
b7a3d63883d242fb2525877c6382681c57a0a142
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/MessageHandler.java#L89-L95
19,235
reactor/reactor-netty
src/main/java/reactor/netty/tcp/ProxyProvider.java
ProxyProvider.findProxySupport
@Nullable public static ProxyProvider findProxySupport(Bootstrap b) { ProxyProvider.DeferredProxySupport proxy = BootstrapHandlers.findConfiguration(ProxyProvider.DeferredProxySupport.class, b.config().handler()); if (proxy == null) { return null; } return proxy.proxyProvider; }
java
@Nullable public static ProxyProvider findProxySupport(Bootstrap b) { ProxyProvider.DeferredProxySupport proxy = BootstrapHandlers.findConfiguration(ProxyProvider.DeferredProxySupport.class, b.config().handler()); if (proxy == null) { return null; } return proxy.proxyProvider; }
[ "@", "Nullable", "public", "static", "ProxyProvider", "findProxySupport", "(", "Bootstrap", "b", ")", "{", "ProxyProvider", ".", "DeferredProxySupport", "proxy", "=", "BootstrapHandlers", ".", "findConfiguration", "(", "ProxyProvider", ".", "DeferredProxySupport", ".", "class", ",", "b", ".", "config", "(", ")", ".", "handler", "(", ")", ")", ";", "if", "(", "proxy", "==", "null", ")", "{", "return", "null", ";", "}", "return", "proxy", ".", "proxyProvider", ";", "}" ]
Find Proxy support in the given client bootstrap @param b a bootstrap to search @return any {@link ProxyProvider} found or null
[ "Find", "Proxy", "support", "in", "the", "given", "client", "bootstrap" ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/ProxyProvider.java#L66-L75
19,236
reactor/reactor-netty
src/main/java/reactor/netty/tcp/ProxyProvider.java
ProxyProvider.shouldProxy
public boolean shouldProxy(SocketAddress address) { SocketAddress addr = address; if (address instanceof TcpUtils.SocketAddressSupplier) { addr = ((TcpUtils.SocketAddressSupplier) address).get(); } return addr instanceof InetSocketAddress && shouldProxy(((InetSocketAddress) addr).getHostString()); }
java
public boolean shouldProxy(SocketAddress address) { SocketAddress addr = address; if (address instanceof TcpUtils.SocketAddressSupplier) { addr = ((TcpUtils.SocketAddressSupplier) address).get(); } return addr instanceof InetSocketAddress && shouldProxy(((InetSocketAddress) addr).getHostString()); }
[ "public", "boolean", "shouldProxy", "(", "SocketAddress", "address", ")", "{", "SocketAddress", "addr", "=", "address", ";", "if", "(", "address", "instanceof", "TcpUtils", ".", "SocketAddressSupplier", ")", "{", "addr", "=", "(", "(", "TcpUtils", ".", "SocketAddressSupplier", ")", "address", ")", ".", "get", "(", ")", ";", "}", "return", "addr", "instanceof", "InetSocketAddress", "&&", "shouldProxy", "(", "(", "(", "InetSocketAddress", ")", "addr", ")", ".", "getHostString", "(", ")", ")", ";", "}" ]
Should proxy the given address @param address the address to test @return true if of type {@link InetSocketAddress} and hostname candidate to proxy
[ "Should", "proxy", "the", "given", "address" ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/ProxyProvider.java#L174-L180
19,237
reactor/reactor-netty
src/main/java/reactor/netty/udp/UdpServer.java
UdpServer.host
public final UdpServer host(String host) { Objects.requireNonNull(host, "host"); return bootstrap(b -> b.localAddress(host, getPort(b))); }
java
public final UdpServer host(String host) { Objects.requireNonNull(host, "host"); return bootstrap(b -> b.localAddress(host, getPort(b))); }
[ "public", "final", "UdpServer", "host", "(", "String", "host", ")", "{", "Objects", ".", "requireNonNull", "(", "host", ",", "\"host\"", ")", ";", "return", "bootstrap", "(", "b", "->", "b", ".", "localAddress", "(", "host", ",", "getPort", "(", "b", ")", ")", ")", ";", "}" ]
The host to which this server should bind. @param host The host to bind to. @return a new {@link UdpServer}
[ "The", "host", "to", "which", "this", "server", "should", "bind", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/udp/UdpServer.java#L258-L261
19,238
reactor/reactor-netty
src/main/java/reactor/netty/udp/UdpServer.java
UdpServer.port
public final UdpServer port(int port) { return bootstrap(b -> b.localAddress(getHost(b), port)); }
java
public final UdpServer port(int port) { return bootstrap(b -> b.localAddress(getHost(b), port)); }
[ "public", "final", "UdpServer", "port", "(", "int", "port", ")", "{", "return", "bootstrap", "(", "b", "->", "b", ".", "localAddress", "(", "getHost", "(", "b", ")", ",", "port", ")", ")", ";", "}" ]
The port to which this server should bind. @param port The port to bind to. @return a new {@link UdpServer}
[ "The", "port", "to", "which", "this", "server", "should", "bind", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/udp/UdpServer.java#L300-L302
19,239
reactor/reactor-netty
src/main/java/reactor/netty/udp/UdpServer.java
UdpServer.wiretap
public final UdpServer wiretap(String category, LogLevel level) { Objects.requireNonNull(category, "category"); Objects.requireNonNull(level, "level"); return bootstrap(b -> BootstrapHandlers.updateLogSupport(b, new LoggingHandler(category, level))); }
java
public final UdpServer wiretap(String category, LogLevel level) { Objects.requireNonNull(category, "category"); Objects.requireNonNull(level, "level"); return bootstrap(b -> BootstrapHandlers.updateLogSupport(b, new LoggingHandler(category, level))); }
[ "public", "final", "UdpServer", "wiretap", "(", "String", "category", ",", "LogLevel", "level", ")", "{", "Objects", ".", "requireNonNull", "(", "category", ",", "\"category\"", ")", ";", "Objects", ".", "requireNonNull", "(", "level", ",", "\"level\"", ")", ";", "return", "bootstrap", "(", "b", "->", "BootstrapHandlers", ".", "updateLogSupport", "(", "b", ",", "new", "LoggingHandler", "(", "category", ",", "level", ")", ")", ")", ";", "}" ]
Apply a wire logger configuration using the specified category and logger level @param category the logger category @param level the logger level @return a new {@link UdpServer}
[ "Apply", "a", "wire", "logger", "configuration", "using", "the", "specified", "category", "and", "logger", "level" ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/udp/UdpServer.java#L396-L401
19,240
reactor/reactor-netty
src/main/java/reactor/netty/channel/AbortedException.java
AbortedException.isConnectionReset
public static boolean isConnectionReset(Throwable err) { return err instanceof AbortedException || (err instanceof IOException && (err.getMessage() == null || err.getMessage() .contains("Broken pipe") || err.getMessage() .contains("Connection reset by peer"))) || (err instanceof SocketException && err.getMessage() != null && err.getMessage() .contains("Connection reset by peer")); }
java
public static boolean isConnectionReset(Throwable err) { return err instanceof AbortedException || (err instanceof IOException && (err.getMessage() == null || err.getMessage() .contains("Broken pipe") || err.getMessage() .contains("Connection reset by peer"))) || (err instanceof SocketException && err.getMessage() != null && err.getMessage() .contains("Connection reset by peer")); }
[ "public", "static", "boolean", "isConnectionReset", "(", "Throwable", "err", ")", "{", "return", "err", "instanceof", "AbortedException", "||", "(", "err", "instanceof", "IOException", "&&", "(", "err", ".", "getMessage", "(", ")", "==", "null", "||", "err", ".", "getMessage", "(", ")", ".", "contains", "(", "\"Broken pipe\"", ")", "||", "err", ".", "getMessage", "(", ")", ".", "contains", "(", "\"Connection reset by peer\"", ")", ")", ")", "||", "(", "err", "instanceof", "SocketException", "&&", "err", ".", "getMessage", "(", ")", "!=", "null", "&&", "err", ".", "getMessage", "(", ")", ".", "contains", "(", "\"Connection reset by peer\"", ")", ")", ";", "}" ]
Return true if connection has been simply aborted on a tcp level by verifying if the given inbound error. @param err an inbound exception @return true if connection has been simply aborted on a tcp level
[ "Return", "true", "if", "connection", "has", "been", "simply", "aborted", "on", "a", "tcp", "level", "by", "verifying", "if", "the", "given", "inbound", "error", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/channel/AbortedException.java#L42-L52
19,241
reactor/reactor-netty
src/main/java/reactor/netty/http/Cookies.java
Cookies.newServerRequestHolder
public static Cookies newServerRequestHolder(HttpHeaders headers, ServerCookieDecoder decoder) { return new Cookies(headers, HttpHeaderNames.COOKIE, false, decoder); }
java
public static Cookies newServerRequestHolder(HttpHeaders headers, ServerCookieDecoder decoder) { return new Cookies(headers, HttpHeaderNames.COOKIE, false, decoder); }
[ "public", "static", "Cookies", "newServerRequestHolder", "(", "HttpHeaders", "headers", ",", "ServerCookieDecoder", "decoder", ")", "{", "return", "new", "Cookies", "(", "headers", ",", "HttpHeaderNames", ".", "COOKIE", ",", "false", ",", "decoder", ")", ";", "}" ]
Return a new cookies holder from server request headers @param headers server request headers @return a new cookies holder from server request headers
[ "Return", "a", "new", "cookies", "holder", "from", "server", "request", "headers" ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/Cookies.java#L55-L57
19,242
reactor/reactor-netty
src/main/java/reactor/netty/http/Cookies.java
Cookies.getCachedCookies
public Map<CharSequence, Set<Cookie>> getCachedCookies() { if (!STATE.compareAndSet(this, NOT_READ, READING)) { for (; ; ) { if (state == READ) { return cachedCookies; } } } List<String> allCookieHeaders = nettyHeaders.getAll(cookiesHeaderName); Map<String, Set<Cookie>> cookies = new HashMap<>(); for (String aCookieHeader : allCookieHeaders) { Set<Cookie> decode; if (isClientChannel) { final Cookie c = ((ClientCookieDecoder) decoder).decode(aCookieHeader); Set<Cookie> existingCookiesOfName = cookies.get(c.name()); if (null == existingCookiesOfName) { existingCookiesOfName = new HashSet<>(); cookies.put(c.name(), existingCookiesOfName); } existingCookiesOfName.add(c); } else { decode = ((ServerCookieDecoder) decoder).decode(aCookieHeader); for (Cookie cookie : decode) { Set<Cookie> existingCookiesOfName = cookies.get(cookie.name()); if (null == existingCookiesOfName) { existingCookiesOfName = new HashSet<>(); cookies.put(cookie.name(), existingCookiesOfName); } existingCookiesOfName.add(cookie); } } } cachedCookies = Collections.unmodifiableMap(cookies); state = READ; return cachedCookies; }
java
public Map<CharSequence, Set<Cookie>> getCachedCookies() { if (!STATE.compareAndSet(this, NOT_READ, READING)) { for (; ; ) { if (state == READ) { return cachedCookies; } } } List<String> allCookieHeaders = nettyHeaders.getAll(cookiesHeaderName); Map<String, Set<Cookie>> cookies = new HashMap<>(); for (String aCookieHeader : allCookieHeaders) { Set<Cookie> decode; if (isClientChannel) { final Cookie c = ((ClientCookieDecoder) decoder).decode(aCookieHeader); Set<Cookie> existingCookiesOfName = cookies.get(c.name()); if (null == existingCookiesOfName) { existingCookiesOfName = new HashSet<>(); cookies.put(c.name(), existingCookiesOfName); } existingCookiesOfName.add(c); } else { decode = ((ServerCookieDecoder) decoder).decode(aCookieHeader); for (Cookie cookie : decode) { Set<Cookie> existingCookiesOfName = cookies.get(cookie.name()); if (null == existingCookiesOfName) { existingCookiesOfName = new HashSet<>(); cookies.put(cookie.name(), existingCookiesOfName); } existingCookiesOfName.add(cookie); } } } cachedCookies = Collections.unmodifiableMap(cookies); state = READ; return cachedCookies; }
[ "public", "Map", "<", "CharSequence", ",", "Set", "<", "Cookie", ">", ">", "getCachedCookies", "(", ")", "{", "if", "(", "!", "STATE", ".", "compareAndSet", "(", "this", ",", "NOT_READ", ",", "READING", ")", ")", "{", "for", "(", ";", ";", ")", "{", "if", "(", "state", "==", "READ", ")", "{", "return", "cachedCookies", ";", "}", "}", "}", "List", "<", "String", ">", "allCookieHeaders", "=", "nettyHeaders", ".", "getAll", "(", "cookiesHeaderName", ")", ";", "Map", "<", "String", ",", "Set", "<", "Cookie", ">", ">", "cookies", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "String", "aCookieHeader", ":", "allCookieHeaders", ")", "{", "Set", "<", "Cookie", ">", "decode", ";", "if", "(", "isClientChannel", ")", "{", "final", "Cookie", "c", "=", "(", "(", "ClientCookieDecoder", ")", "decoder", ")", ".", "decode", "(", "aCookieHeader", ")", ";", "Set", "<", "Cookie", ">", "existingCookiesOfName", "=", "cookies", ".", "get", "(", "c", ".", "name", "(", ")", ")", ";", "if", "(", "null", "==", "existingCookiesOfName", ")", "{", "existingCookiesOfName", "=", "new", "HashSet", "<>", "(", ")", ";", "cookies", ".", "put", "(", "c", ".", "name", "(", ")", ",", "existingCookiesOfName", ")", ";", "}", "existingCookiesOfName", ".", "add", "(", "c", ")", ";", "}", "else", "{", "decode", "=", "(", "(", "ServerCookieDecoder", ")", "decoder", ")", ".", "decode", "(", "aCookieHeader", ")", ";", "for", "(", "Cookie", "cookie", ":", "decode", ")", "{", "Set", "<", "Cookie", ">", "existingCookiesOfName", "=", "cookies", ".", "get", "(", "cookie", ".", "name", "(", ")", ")", ";", "if", "(", "null", "==", "existingCookiesOfName", ")", "{", "existingCookiesOfName", "=", "new", "HashSet", "<>", "(", ")", ";", "cookies", ".", "put", "(", "cookie", ".", "name", "(", ")", ",", "existingCookiesOfName", ")", ";", "}", "existingCookiesOfName", ".", "add", "(", "cookie", ")", ";", "}", "}", "}", "cachedCookies", "=", "Collections", ".", "unmodifiableMap", "(", "cookies", ")", ";", "state", "=", "READ", ";", "return", "cachedCookies", ";", "}" ]
Wait for the cookies to become available, cache them and subsequently return the cached map of cookies.
[ "Wait", "for", "the", "cookies", "to", "become", "available", "cache", "them", "and", "subsequently", "return", "the", "cached", "map", "of", "cookies", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/Cookies.java#L90-L127
19,243
reactor/reactor-netty
src/main/java/reactor/netty/udp/UdpClient.java
UdpClient.addressSupplier
public final UdpClient addressSupplier(Supplier<? extends SocketAddress> connectingAddressSupplier) { Objects.requireNonNull(connectingAddressSupplier, "connectingAddressSupplier"); return bootstrap(b -> b.remoteAddress(connectingAddressSupplier.get())); }
java
public final UdpClient addressSupplier(Supplier<? extends SocketAddress> connectingAddressSupplier) { Objects.requireNonNull(connectingAddressSupplier, "connectingAddressSupplier"); return bootstrap(b -> b.remoteAddress(connectingAddressSupplier.get())); }
[ "public", "final", "UdpClient", "addressSupplier", "(", "Supplier", "<", "?", "extends", "SocketAddress", ">", "connectingAddressSupplier", ")", "{", "Objects", ".", "requireNonNull", "(", "connectingAddressSupplier", ",", "\"connectingAddressSupplier\"", ")", ";", "return", "bootstrap", "(", "b", "->", "b", ".", "remoteAddress", "(", "connectingAddressSupplier", ".", "get", "(", ")", ")", ")", ";", "}" ]
The address to which this client should connect on subscribe. @param connectingAddressSupplier A supplier of the address to connect to. @return a new {@link UdpClient}
[ "The", "address", "to", "which", "this", "client", "should", "connect", "on", "subscribe", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/udp/UdpClient.java#L91-L94
19,244
reactor/reactor-netty
src/main/java/reactor/netty/udp/UdpClient.java
UdpClient.port
public final UdpClient port(int port) { return bootstrap(b -> b.remoteAddress(getHost(b), port)); }
java
public final UdpClient port(int port) { return bootstrap(b -> b.remoteAddress(getHost(b), port)); }
[ "public", "final", "UdpClient", "port", "(", "int", "port", ")", "{", "return", "bootstrap", "(", "b", "->", "b", ".", "remoteAddress", "(", "getHost", "(", "b", ")", ",", "port", ")", ")", ";", "}" ]
The port to which this client should connect. @param port The port to connect to. @return a new {@link UdpClient}
[ "The", "port", "to", "which", "this", "client", "should", "connect", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/udp/UdpClient.java#L299-L301
19,245
reactor/reactor-netty
src/main/java/reactor/netty/tcp/InetSocketAddressUtil.java
InetSocketAddressUtil.createInetSocketAddress
public static InetSocketAddress createInetSocketAddress(String hostname, int port, boolean resolve) { InetSocketAddress inetAddressForIpString = createForIpString(hostname, port); if (inetAddressForIpString != null) { return inetAddressForIpString; } else { return resolve ? new InetSocketAddress(hostname, port) : InetSocketAddress.createUnresolved(hostname, port); } }
java
public static InetSocketAddress createInetSocketAddress(String hostname, int port, boolean resolve) { InetSocketAddress inetAddressForIpString = createForIpString(hostname, port); if (inetAddressForIpString != null) { return inetAddressForIpString; } else { return resolve ? new InetSocketAddress(hostname, port) : InetSocketAddress.createUnresolved(hostname, port); } }
[ "public", "static", "InetSocketAddress", "createInetSocketAddress", "(", "String", "hostname", ",", "int", "port", ",", "boolean", "resolve", ")", "{", "InetSocketAddress", "inetAddressForIpString", "=", "createForIpString", "(", "hostname", ",", "port", ")", ";", "if", "(", "inetAddressForIpString", "!=", "null", ")", "{", "return", "inetAddressForIpString", ";", "}", "else", "{", "return", "resolve", "?", "new", "InetSocketAddress", "(", "hostname", ",", "port", ")", ":", "InetSocketAddress", ".", "createUnresolved", "(", "hostname", ",", "port", ")", ";", "}", "}" ]
Creates InetSocketAddress instance. Numeric IP addresses will be detected and resolved without doing reverse DNS lookups. @param hostname ip-address or hostname @param port port number @param resolve when true, resolve given hostname at instance creation time @return InetSocketAddress for given parameters
[ "Creates", "InetSocketAddress", "instance", ".", "Numeric", "IP", "addresses", "will", "be", "detected", "and", "resolved", "without", "doing", "reverse", "DNS", "lookups", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/InetSocketAddressUtil.java#L72-L82
19,246
reactor/reactor-netty
src/main/java/reactor/netty/tcp/InetSocketAddressUtil.java
InetSocketAddressUtil.replaceWithResolved
public static InetSocketAddress replaceWithResolved( InetSocketAddress inetSocketAddress) { if (!inetSocketAddress.isUnresolved()) { return inetSocketAddress; } inetSocketAddress = replaceUnresolvedNumericIp(inetSocketAddress); if (!inetSocketAddress.isUnresolved()) { return inetSocketAddress; } else { return new InetSocketAddress(inetSocketAddress.getHostString(), inetSocketAddress.getPort()); } }
java
public static InetSocketAddress replaceWithResolved( InetSocketAddress inetSocketAddress) { if (!inetSocketAddress.isUnresolved()) { return inetSocketAddress; } inetSocketAddress = replaceUnresolvedNumericIp(inetSocketAddress); if (!inetSocketAddress.isUnresolved()) { return inetSocketAddress; } else { return new InetSocketAddress(inetSocketAddress.getHostString(), inetSocketAddress.getPort()); } }
[ "public", "static", "InetSocketAddress", "replaceWithResolved", "(", "InetSocketAddress", "inetSocketAddress", ")", "{", "if", "(", "!", "inetSocketAddress", ".", "isUnresolved", "(", ")", ")", "{", "return", "inetSocketAddress", ";", "}", "inetSocketAddress", "=", "replaceUnresolvedNumericIp", "(", "inetSocketAddress", ")", ";", "if", "(", "!", "inetSocketAddress", ".", "isUnresolved", "(", ")", ")", "{", "return", "inetSocketAddress", ";", "}", "else", "{", "return", "new", "InetSocketAddress", "(", "inetSocketAddress", ".", "getHostString", "(", ")", ",", "inetSocketAddress", ".", "getPort", "(", ")", ")", ";", "}", "}" ]
Replaces an unresolved InetSocketAddress with a resolved instance in the case that the passed address is unresolved. @param inetSocketAddress socket address instance to process @return resolved instance with same host string and port
[ "Replaces", "an", "unresolved", "InetSocketAddress", "with", "a", "resolved", "instance", "in", "the", "case", "that", "the", "passed", "address", "is", "unresolved", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/InetSocketAddressUtil.java#L100-L113
19,247
reactor/reactor-netty
src/main/java/reactor/netty/tcp/TcpServer.java
TcpServer.addressSupplier
public final TcpServer addressSupplier(Supplier<? extends SocketAddress> bindingAddressSupplier) { Objects.requireNonNull(bindingAddressSupplier, "bindingAddressSupplier"); return bootstrap(b -> b.localAddress(bindingAddressSupplier.get())); }
java
public final TcpServer addressSupplier(Supplier<? extends SocketAddress> bindingAddressSupplier) { Objects.requireNonNull(bindingAddressSupplier, "bindingAddressSupplier"); return bootstrap(b -> b.localAddress(bindingAddressSupplier.get())); }
[ "public", "final", "TcpServer", "addressSupplier", "(", "Supplier", "<", "?", "extends", "SocketAddress", ">", "bindingAddressSupplier", ")", "{", "Objects", ".", "requireNonNull", "(", "bindingAddressSupplier", ",", "\"bindingAddressSupplier\"", ")", ";", "return", "bootstrap", "(", "b", "->", "b", ".", "localAddress", "(", "bindingAddressSupplier", ".", "get", "(", ")", ")", ")", ";", "}" ]
The address to which this server should bind on subscribe. @param bindingAddressSupplier A supplier of the address to bind to. @return a new {@link TcpServer}
[ "The", "address", "to", "which", "this", "server", "should", "bind", "on", "subscribe", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/TcpServer.java#L93-L96
19,248
reactor/reactor-netty
src/main/java/reactor/netty/ByteBufFlux.java
ByteBufFlux.aggregate
public ByteBufMono aggregate() { return Mono.using(alloc::compositeBuffer, b -> this.reduce(b, (prev, next) -> { if (prev.refCnt() > 0) { return prev.addComponent(true, next.retain()); } else { return prev; } }) .filter(ByteBuf::isReadable), b -> { if (b.refCnt() > 0) { b.release(); } }) .as(ByteBufMono::new); }
java
public ByteBufMono aggregate() { return Mono.using(alloc::compositeBuffer, b -> this.reduce(b, (prev, next) -> { if (prev.refCnt() > 0) { return prev.addComponent(true, next.retain()); } else { return prev; } }) .filter(ByteBuf::isReadable), b -> { if (b.refCnt() > 0) { b.release(); } }) .as(ByteBufMono::new); }
[ "public", "ByteBufMono", "aggregate", "(", ")", "{", "return", "Mono", ".", "using", "(", "alloc", "::", "compositeBuffer", ",", "b", "->", "this", ".", "reduce", "(", "b", ",", "(", "prev", ",", "next", ")", "->", "{", "if", "(", "prev", ".", "refCnt", "(", ")", ">", "0", ")", "{", "return", "prev", ".", "addComponent", "(", "true", ",", "next", ".", "retain", "(", ")", ")", ";", "}", "else", "{", "return", "prev", ";", "}", "}", ")", ".", "filter", "(", "ByteBuf", "::", "isReadable", ")", ",", "b", "->", "{", "if", "(", "b", ".", "refCnt", "(", ")", ">", "0", ")", "{", "b", ".", "release", "(", ")", ";", "}", "}", ")", ".", "as", "(", "ByteBufMono", "::", "new", ")", ";", "}" ]
Aggregate subsequent byte buffers into a single buffer. @return {@link ByteBufMono} of aggregated {@link ByteBuf}
[ "Aggregate", "subsequent", "byte", "buffers", "into", "a", "single", "buffer", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/ByteBufFlux.java#L257-L275
19,249
reactor/reactor-netty
src/main/java/reactor/netty/udp/UdpOperations.java
UdpOperations.join
@Override public Mono<Void> join(final InetAddress multicastAddress, NetworkInterface iface) { if (null == iface && null != datagramChannel.config().getNetworkInterface()) { iface = datagramChannel.config().getNetworkInterface(); } final ChannelFuture future; if (null != iface) { future = datagramChannel.joinGroup(new InetSocketAddress(multicastAddress, datagramChannel.localAddress() .getPort()), iface); } else { future = datagramChannel.joinGroup(multicastAddress); } return FutureMono.from(future) .doOnSuccess(v -> { if (log.isInfoEnabled()) { log.info(format(future.channel(), "JOIN {}"), multicastAddress); } }); }
java
@Override public Mono<Void> join(final InetAddress multicastAddress, NetworkInterface iface) { if (null == iface && null != datagramChannel.config().getNetworkInterface()) { iface = datagramChannel.config().getNetworkInterface(); } final ChannelFuture future; if (null != iface) { future = datagramChannel.joinGroup(new InetSocketAddress(multicastAddress, datagramChannel.localAddress() .getPort()), iface); } else { future = datagramChannel.joinGroup(multicastAddress); } return FutureMono.from(future) .doOnSuccess(v -> { if (log.isInfoEnabled()) { log.info(format(future.channel(), "JOIN {}"), multicastAddress); } }); }
[ "@", "Override", "public", "Mono", "<", "Void", ">", "join", "(", "final", "InetAddress", "multicastAddress", ",", "NetworkInterface", "iface", ")", "{", "if", "(", "null", "==", "iface", "&&", "null", "!=", "datagramChannel", ".", "config", "(", ")", ".", "getNetworkInterface", "(", ")", ")", "{", "iface", "=", "datagramChannel", ".", "config", "(", ")", ".", "getNetworkInterface", "(", ")", ";", "}", "final", "ChannelFuture", "future", ";", "if", "(", "null", "!=", "iface", ")", "{", "future", "=", "datagramChannel", ".", "joinGroup", "(", "new", "InetSocketAddress", "(", "multicastAddress", ",", "datagramChannel", ".", "localAddress", "(", ")", ".", "getPort", "(", ")", ")", ",", "iface", ")", ";", "}", "else", "{", "future", "=", "datagramChannel", ".", "joinGroup", "(", "multicastAddress", ")", ";", "}", "return", "FutureMono", ".", "from", "(", "future", ")", ".", "doOnSuccess", "(", "v", "->", "{", "if", "(", "log", ".", "isInfoEnabled", "(", ")", ")", "{", "log", ".", "info", "(", "format", "(", "future", ".", "channel", "(", ")", ",", "\"JOIN {}\"", ")", ",", "multicastAddress", ")", ";", "}", "}", ")", ";", "}" ]
Join a multicast group. @param multicastAddress multicast address of the group to join @return a {@link Publisher} that will be complete when the group has been joined
[ "Join", "a", "multicast", "group", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/udp/UdpOperations.java#L57-L79
19,250
reactor/reactor-netty
src/main/java/reactor/netty/http/client/HttpClient.java
HttpClient.mapConnect
public final HttpClient mapConnect(BiFunction<? super Mono<? extends Connection>, ? super Bootstrap, ? extends Mono<? extends Connection>> connector) { return new HttpClientOnConnectMap(this, connector); }
java
public final HttpClient mapConnect(BiFunction<? super Mono<? extends Connection>, ? super Bootstrap, ? extends Mono<? extends Connection>> connector) { return new HttpClientOnConnectMap(this, connector); }
[ "public", "final", "HttpClient", "mapConnect", "(", "BiFunction", "<", "?", "super", "Mono", "<", "?", "extends", "Connection", ">", ",", "?", "super", "Bootstrap", ",", "?", "extends", "Mono", "<", "?", "extends", "Connection", ">", ">", "connector", ")", "{", "return", "new", "HttpClientOnConnectMap", "(", "this", ",", "connector", ")", ";", "}" ]
Intercept the connection lifecycle and allows to delay, transform or inject a context. @param connector A bi function mapping the default connection and configured bootstrap to a target connection. @return a new {@link HttpClient}
[ "Intercept", "the", "connection", "lifecycle", "and", "allows", "to", "delay", "transform", "or", "inject", "a", "context", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/client/HttpClient.java#L413-L415
19,251
reactor/reactor-netty
src/main/java/reactor/netty/http/client/HttpClient.java
HttpClient.cookie
public final HttpClient cookie(String name, Consumer<? super Cookie> cookieBuilder) { return new HttpClientCookie(this, name, cookieBuilder); }
java
public final HttpClient cookie(String name, Consumer<? super Cookie> cookieBuilder) { return new HttpClientCookie(this, name, cookieBuilder); }
[ "public", "final", "HttpClient", "cookie", "(", "String", "name", ",", "Consumer", "<", "?", "super", "Cookie", ">", "cookieBuilder", ")", "{", "return", "new", "HttpClientCookie", "(", "this", ",", "name", ",", "cookieBuilder", ")", ";", "}" ]
Apply cookies configuration. @param cookieBuilder the header {@link Consumer} to invoke before requesting @return a new {@link HttpClient}
[ "Apply", "cookies", "configuration", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/client/HttpClient.java#L435-L437
19,252
reactor/reactor-netty
src/main/java/reactor/netty/http/client/HttpClient.java
HttpClient.cookiesWhen
public final HttpClient cookiesWhen(String name, Function<? super Cookie, Mono<? extends Cookie>> cookieBuilder) { return new HttpClientCookieWhen(this, name, cookieBuilder); }
java
public final HttpClient cookiesWhen(String name, Function<? super Cookie, Mono<? extends Cookie>> cookieBuilder) { return new HttpClientCookieWhen(this, name, cookieBuilder); }
[ "public", "final", "HttpClient", "cookiesWhen", "(", "String", "name", ",", "Function", "<", "?", "super", "Cookie", ",", "Mono", "<", "?", "extends", "Cookie", ">", ">", "cookieBuilder", ")", "{", "return", "new", "HttpClientCookieWhen", "(", "this", ",", "name", ",", "cookieBuilder", ")", ";", "}" ]
Apply cookies configuration emitted by the returned Mono before requesting. @param cookieBuilder the cookies {@link Function} to invoke before sending @return a new {@link HttpClient}
[ "Apply", "cookies", "configuration", "emitted", "by", "the", "returned", "Mono", "before", "requesting", "." ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/client/HttpClient.java#L446-L448
19,253
reactor/reactor-netty
src/main/java/reactor/netty/http/server/ConnectionInfo.java
ConnectionInfo.newConnectionInfo
static ConnectionInfo newConnectionInfo(Channel c) { SocketChannel channel = (SocketChannel) c; InetSocketAddress hostAddress = channel.localAddress(); InetSocketAddress remoteAddress = getRemoteAddress(channel); String scheme = channel.pipeline().get(SslHandler.class) != null ? "https" : "http"; return new ConnectionInfo(hostAddress, remoteAddress, scheme); }
java
static ConnectionInfo newConnectionInfo(Channel c) { SocketChannel channel = (SocketChannel) c; InetSocketAddress hostAddress = channel.localAddress(); InetSocketAddress remoteAddress = getRemoteAddress(channel); String scheme = channel.pipeline().get(SslHandler.class) != null ? "https" : "http"; return new ConnectionInfo(hostAddress, remoteAddress, scheme); }
[ "static", "ConnectionInfo", "newConnectionInfo", "(", "Channel", "c", ")", "{", "SocketChannel", "channel", "=", "(", "SocketChannel", ")", "c", ";", "InetSocketAddress", "hostAddress", "=", "channel", ".", "localAddress", "(", ")", ";", "InetSocketAddress", "remoteAddress", "=", "getRemoteAddress", "(", "channel", ")", ";", "String", "scheme", "=", "channel", ".", "pipeline", "(", ")", ".", "get", "(", "SslHandler", ".", "class", ")", "!=", "null", "?", "\"https\"", ":", "\"http\"", ";", "return", "new", "ConnectionInfo", "(", "hostAddress", ",", "remoteAddress", ",", "scheme", ")", ";", "}" ]
Retrieve the connection information from the current connection directly @param c the current channel @return the connection information
[ "Retrieve", "the", "connection", "information", "from", "the", "current", "connection", "directly" ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/server/ConnectionInfo.java#L77-L83
19,254
reactor/reactor-netty
src/main/java/reactor/netty/tcp/SslProvider.java
SslProvider.findSslSupport
@Nullable public static SslProvider findSslSupport(Bootstrap b) { DeferredSslSupport ssl = BootstrapHandlers.findConfiguration(DeferredSslSupport.class, b.config().handler()); if (ssl == null) { return null; } return ssl.sslProvider; }
java
@Nullable public static SslProvider findSslSupport(Bootstrap b) { DeferredSslSupport ssl = BootstrapHandlers.findConfiguration(DeferredSslSupport.class, b.config().handler()); if (ssl == null) { return null; } return ssl.sslProvider; }
[ "@", "Nullable", "public", "static", "SslProvider", "findSslSupport", "(", "Bootstrap", "b", ")", "{", "DeferredSslSupport", "ssl", "=", "BootstrapHandlers", ".", "findConfiguration", "(", "DeferredSslSupport", ".", "class", ",", "b", ".", "config", "(", ")", ".", "handler", "(", ")", ")", ";", "if", "(", "ssl", "==", "null", ")", "{", "return", "null", ";", "}", "return", "ssl", ".", "sslProvider", ";", "}" ]
Find Ssl support in the given client bootstrap @param b a bootstrap to search @return any {@link SslProvider} found or null
[ "Find", "Ssl", "support", "in", "the", "given", "client", "bootstrap" ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/SslProvider.java#L119-L127
19,255
reactor/reactor-netty
src/main/java/reactor/netty/tcp/SslProvider.java
SslProvider.findSslSupport
@Nullable public static SslProvider findSslSupport(ServerBootstrap b) { SslSupportConsumer ssl = BootstrapHandlers.findConfiguration(SslSupportConsumer.class, b.config().childHandler()); if (ssl == null) { return null; } return ssl.sslProvider; }
java
@Nullable public static SslProvider findSslSupport(ServerBootstrap b) { SslSupportConsumer ssl = BootstrapHandlers.findConfiguration(SslSupportConsumer.class, b.config().childHandler()); if (ssl == null) { return null; } return ssl.sslProvider; }
[ "@", "Nullable", "public", "static", "SslProvider", "findSslSupport", "(", "ServerBootstrap", "b", ")", "{", "SslSupportConsumer", "ssl", "=", "BootstrapHandlers", ".", "findConfiguration", "(", "SslSupportConsumer", ".", "class", ",", "b", ".", "config", "(", ")", ".", "childHandler", "(", ")", ")", ";", "if", "(", "ssl", "==", "null", ")", "{", "return", "null", ";", "}", "return", "ssl", ".", "sslProvider", ";", "}" ]
Find Ssl support in the given server bootstrap @param b a bootstrap to search @return any {@link SslProvider} found or null
[ "Find", "Ssl", "support", "in", "the", "given", "server", "bootstrap" ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/SslProvider.java#L136-L144
19,256
reactor/reactor-netty
src/main/java/reactor/netty/tcp/SslProvider.java
SslProvider.removeSslSupport
public static Bootstrap removeSslSupport(Bootstrap b) { BootstrapHandlers.removeConfiguration(b, NettyPipeline.SslHandler); return b; }
java
public static Bootstrap removeSslSupport(Bootstrap b) { BootstrapHandlers.removeConfiguration(b, NettyPipeline.SslHandler); return b; }
[ "public", "static", "Bootstrap", "removeSslSupport", "(", "Bootstrap", "b", ")", "{", "BootstrapHandlers", ".", "removeConfiguration", "(", "b", ",", "NettyPipeline", ".", "SslHandler", ")", ";", "return", "b", ";", "}" ]
Remove Ssl support in the given client bootstrap @param b a bootstrap to search and remove @return passed {@link Bootstrap}
[ "Remove", "Ssl", "support", "in", "the", "given", "client", "bootstrap" ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/SslProvider.java#L153-L156
19,257
reactor/reactor-netty
src/main/java/reactor/netty/http/server/HttpServer.java
HttpServer.compress
public final HttpServer compress(int minResponseSize) { if (minResponseSize < 0) { throw new IllegalArgumentException("minResponseSize must be positive"); } return tcpConfiguration(tcp -> tcp.bootstrap(b -> HttpServerConfiguration.compressSize(b, minResponseSize))); }
java
public final HttpServer compress(int minResponseSize) { if (minResponseSize < 0) { throw new IllegalArgumentException("minResponseSize must be positive"); } return tcpConfiguration(tcp -> tcp.bootstrap(b -> HttpServerConfiguration.compressSize(b, minResponseSize))); }
[ "public", "final", "HttpServer", "compress", "(", "int", "minResponseSize", ")", "{", "if", "(", "minResponseSize", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"minResponseSize must be positive\"", ")", ";", "}", "return", "tcpConfiguration", "(", "tcp", "->", "tcp", ".", "bootstrap", "(", "b", "->", "HttpServerConfiguration", ".", "compressSize", "(", "b", ",", "minResponseSize", ")", ")", ")", ";", "}" ]
Enable GZip response compression if the client request presents accept encoding headers AND the response reaches a minimum threshold @param minResponseSize compression is performed once response size exceeds the given value in bytes @return a new {@link HttpServer}
[ "Enable", "GZip", "response", "compression", "if", "the", "client", "request", "presents", "accept", "encoding", "headers", "AND", "the", "response", "reaches", "a", "minimum", "threshold" ]
4ed14316e1d7fca3cecd18d6caa5f2251e159e49
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/server/HttpServer.java#L199-L204
19,258
spring-cloud/spring-cloud-sleuth
spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/async/LazyTraceAsyncTaskExecutor.java
LazyTraceAsyncTaskExecutor.spanNamer
private SpanNamer spanNamer() { if (this.spanNamer == null) { try { this.spanNamer = this.beanFactory.getBean(SpanNamer.class); } catch (NoSuchBeanDefinitionException e) { log.warn( "SpanNamer bean not found - will provide a manually created instance"); return new DefaultSpanNamer(); } } return this.spanNamer; }
java
private SpanNamer spanNamer() { if (this.spanNamer == null) { try { this.spanNamer = this.beanFactory.getBean(SpanNamer.class); } catch (NoSuchBeanDefinitionException e) { log.warn( "SpanNamer bean not found - will provide a manually created instance"); return new DefaultSpanNamer(); } } return this.spanNamer; }
[ "private", "SpanNamer", "spanNamer", "(", ")", "{", "if", "(", "this", ".", "spanNamer", "==", "null", ")", "{", "try", "{", "this", ".", "spanNamer", "=", "this", ".", "beanFactory", ".", "getBean", "(", "SpanNamer", ".", "class", ")", ";", "}", "catch", "(", "NoSuchBeanDefinitionException", "e", ")", "{", "log", ".", "warn", "(", "\"SpanNamer bean not found - will provide a manually created instance\"", ")", ";", "return", "new", "DefaultSpanNamer", "(", ")", ";", "}", "}", "return", "this", ".", "spanNamer", ";", "}" ]
due to some race conditions trace keys might not be ready yet
[ "due", "to", "some", "race", "conditions", "trace", "keys", "might", "not", "be", "ready", "yet" ]
f29c05fb8fba33e23aa21bb13aeb13ab8d27b485
https://github.com/spring-cloud/spring-cloud-sleuth/blob/f29c05fb8fba33e23aa21bb13aeb13ab8d27b485/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/async/LazyTraceAsyncTaskExecutor.java#L94-L106
19,259
spring-cloud/spring-cloud-sleuth
spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/grpc/TraceGrpcAutoConfiguration.java
TraceGrpcAutoConfiguration.managedChannelBuilder
@Bean @ConditionalOnMissingBean(SpringAwareManagedChannelBuilder.class) public SpringAwareManagedChannelBuilder managedChannelBuilder( Optional<List<GrpcManagedChannelBuilderCustomizer>> customizers) { return new SpringAwareManagedChannelBuilder(customizers); }
java
@Bean @ConditionalOnMissingBean(SpringAwareManagedChannelBuilder.class) public SpringAwareManagedChannelBuilder managedChannelBuilder( Optional<List<GrpcManagedChannelBuilderCustomizer>> customizers) { return new SpringAwareManagedChannelBuilder(customizers); }
[ "@", "Bean", "@", "ConditionalOnMissingBean", "(", "SpringAwareManagedChannelBuilder", ".", "class", ")", "public", "SpringAwareManagedChannelBuilder", "managedChannelBuilder", "(", "Optional", "<", "List", "<", "GrpcManagedChannelBuilderCustomizer", ">", ">", "customizers", ")", "{", "return", "new", "SpringAwareManagedChannelBuilder", "(", "customizers", ")", ";", "}" ]
This is wrapper around gRPC's managed channel builder that is spring-aware
[ "This", "is", "wrapper", "around", "gRPC", "s", "managed", "channel", "builder", "that", "is", "spring", "-", "aware" ]
f29c05fb8fba33e23aa21bb13aeb13ab8d27b485
https://github.com/spring-cloud/spring-cloud-sleuth/blob/f29c05fb8fba33e23aa21bb13aeb13ab8d27b485/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/grpc/TraceGrpcAutoConfiguration.java#L60-L65
19,260
spring-cloud/spring-cloud-sleuth
spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/annotation/SleuthAnnotationUtils.java
SleuthAnnotationUtils.findAnnotation
static <T extends Annotation> T findAnnotation(Method method, Class<T> clazz) { T annotation = AnnotationUtils.findAnnotation(method, clazz); if (annotation == null) { try { annotation = AnnotationUtils.findAnnotation(method.getDeclaringClass() .getMethod(method.getName(), method.getParameterTypes()), clazz); } catch (NoSuchMethodException | SecurityException ex) { if (log.isDebugEnabled()) { log.debug("Exception occurred while tyring to find the annotation", ex); } } } return annotation; }
java
static <T extends Annotation> T findAnnotation(Method method, Class<T> clazz) { T annotation = AnnotationUtils.findAnnotation(method, clazz); if (annotation == null) { try { annotation = AnnotationUtils.findAnnotation(method.getDeclaringClass() .getMethod(method.getName(), method.getParameterTypes()), clazz); } catch (NoSuchMethodException | SecurityException ex) { if (log.isDebugEnabled()) { log.debug("Exception occurred while tyring to find the annotation", ex); } } } return annotation; }
[ "static", "<", "T", "extends", "Annotation", ">", "T", "findAnnotation", "(", "Method", "method", ",", "Class", "<", "T", ">", "clazz", ")", "{", "T", "annotation", "=", "AnnotationUtils", ".", "findAnnotation", "(", "method", ",", "clazz", ")", ";", "if", "(", "annotation", "==", "null", ")", "{", "try", "{", "annotation", "=", "AnnotationUtils", ".", "findAnnotation", "(", "method", ".", "getDeclaringClass", "(", ")", ".", "getMethod", "(", "method", ".", "getName", "(", ")", ",", "method", ".", "getParameterTypes", "(", ")", ")", ",", "clazz", ")", ";", "}", "catch", "(", "NoSuchMethodException", "|", "SecurityException", "ex", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Exception occurred while tyring to find the annotation\"", ",", "ex", ")", ";", "}", "}", "}", "return", "annotation", ";", "}" ]
Searches for an annotation either on a method or inside the method parameters. @param <T> - annotation @param clazz - class with annotation @param method - annotated method @return annotation
[ "Searches", "for", "an", "annotation", "either", "on", "a", "method", "or", "inside", "the", "method", "parameters", "." ]
f29c05fb8fba33e23aa21bb13aeb13ab8d27b485
https://github.com/spring-cloud/spring-cloud-sleuth/blob/f29c05fb8fba33e23aa21bb13aeb13ab8d27b485/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/annotation/SleuthAnnotationUtils.java#L77-L92
19,261
spring-cloud/spring-cloud-sleuth
spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/messaging/TracingChannelInterceptor.java
TracingChannelInterceptor.postReceive
@Override public Message<?> postReceive(Message<?> message, MessageChannel channel) { if (emptyMessage(message)) { return message; } MessageHeaderAccessor headers = mutableHeaderAccessor(message); TraceContextOrSamplingFlags extracted = this.extractor.extract(headers); Span span = this.threadLocalSpan.next(extracted); MessageHeaderPropagation.removeAnyTraceHeaders(headers, this.tracing.propagation().keys()); this.injector.inject(span.context(), headers); if (!span.isNoop()) { span.kind(Span.Kind.CONSUMER).name("receive").start(); span.remoteServiceName(REMOTE_SERVICE_NAME); addTags(message, span, channel); } if (log.isDebugEnabled()) { log.debug("Created a new span in post receive " + span); } headers.setImmutable(); if (message instanceof ErrorMessage) { ErrorMessage errorMessage = (ErrorMessage) message; return new ErrorMessage(errorMessage.getPayload(), headers.getMessageHeaders(), errorMessage.getOriginalMessage()); } return new GenericMessage<>(message.getPayload(), headers.getMessageHeaders()); }
java
@Override public Message<?> postReceive(Message<?> message, MessageChannel channel) { if (emptyMessage(message)) { return message; } MessageHeaderAccessor headers = mutableHeaderAccessor(message); TraceContextOrSamplingFlags extracted = this.extractor.extract(headers); Span span = this.threadLocalSpan.next(extracted); MessageHeaderPropagation.removeAnyTraceHeaders(headers, this.tracing.propagation().keys()); this.injector.inject(span.context(), headers); if (!span.isNoop()) { span.kind(Span.Kind.CONSUMER).name("receive").start(); span.remoteServiceName(REMOTE_SERVICE_NAME); addTags(message, span, channel); } if (log.isDebugEnabled()) { log.debug("Created a new span in post receive " + span); } headers.setImmutable(); if (message instanceof ErrorMessage) { ErrorMessage errorMessage = (ErrorMessage) message; return new ErrorMessage(errorMessage.getPayload(), headers.getMessageHeaders(), errorMessage.getOriginalMessage()); } return new GenericMessage<>(message.getPayload(), headers.getMessageHeaders()); }
[ "@", "Override", "public", "Message", "<", "?", ">", "postReceive", "(", "Message", "<", "?", ">", "message", ",", "MessageChannel", "channel", ")", "{", "if", "(", "emptyMessage", "(", "message", ")", ")", "{", "return", "message", ";", "}", "MessageHeaderAccessor", "headers", "=", "mutableHeaderAccessor", "(", "message", ")", ";", "TraceContextOrSamplingFlags", "extracted", "=", "this", ".", "extractor", ".", "extract", "(", "headers", ")", ";", "Span", "span", "=", "this", ".", "threadLocalSpan", ".", "next", "(", "extracted", ")", ";", "MessageHeaderPropagation", ".", "removeAnyTraceHeaders", "(", "headers", ",", "this", ".", "tracing", ".", "propagation", "(", ")", ".", "keys", "(", ")", ")", ";", "this", ".", "injector", ".", "inject", "(", "span", ".", "context", "(", ")", ",", "headers", ")", ";", "if", "(", "!", "span", ".", "isNoop", "(", ")", ")", "{", "span", ".", "kind", "(", "Span", ".", "Kind", ".", "CONSUMER", ")", ".", "name", "(", "\"receive\"", ")", ".", "start", "(", ")", ";", "span", ".", "remoteServiceName", "(", "REMOTE_SERVICE_NAME", ")", ";", "addTags", "(", "message", ",", "span", ",", "channel", ")", ";", "}", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Created a new span in post receive \"", "+", "span", ")", ";", "}", "headers", ".", "setImmutable", "(", ")", ";", "if", "(", "message", "instanceof", "ErrorMessage", ")", "{", "ErrorMessage", "errorMessage", "=", "(", "ErrorMessage", ")", "message", ";", "return", "new", "ErrorMessage", "(", "errorMessage", ".", "getPayload", "(", ")", ",", "headers", ".", "getMessageHeaders", "(", ")", ",", "errorMessage", ".", "getOriginalMessage", "(", ")", ")", ";", "}", "return", "new", "GenericMessage", "<>", "(", "message", ".", "getPayload", "(", ")", ",", "headers", ".", "getMessageHeaders", "(", ")", ")", ";", "}" ]
This starts a consumer span as a child of the incoming message or the current trace context, placing it in scope until the receive completes.
[ "This", "starts", "a", "consumer", "span", "as", "a", "child", "of", "the", "incoming", "message", "or", "the", "current", "trace", "context", "placing", "it", "in", "scope", "until", "the", "receive", "completes", "." ]
f29c05fb8fba33e23aa21bb13aeb13ab8d27b485
https://github.com/spring-cloud/spring-cloud-sleuth/blob/f29c05fb8fba33e23aa21bb13aeb13ab8d27b485/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/messaging/TracingChannelInterceptor.java#L253-L279
19,262
spring-cloud/spring-cloud-sleuth
spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/messaging/TracingChannelInterceptor.java
TracingChannelInterceptor.beforeHandle
@Override public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) { if (emptyMessage(message)) { return message; } MessageHeaderAccessor headers = mutableHeaderAccessor(message); TraceContextOrSamplingFlags extracted = this.extractor.extract(headers); // Start and finish a consumer span as we will immediately process it. Span consumerSpan = this.tracer.nextSpan(extracted); if (!consumerSpan.isNoop()) { consumerSpan.kind(Span.Kind.CONSUMER).start(); consumerSpan.remoteServiceName(REMOTE_SERVICE_NAME); addTags(message, consumerSpan, channel); consumerSpan.finish(); } // create and scope a span for the message processor this.threadLocalSpan .next(TraceContextOrSamplingFlags.create(consumerSpan.context())) .name("handle").start(); // remove any trace headers, but don't re-inject as we are synchronously // processing the // message and can rely on scoping to access this span later. MessageHeaderPropagation.removeAnyTraceHeaders(headers, this.tracing.propagation().keys()); if (log.isDebugEnabled()) { log.debug("Created a new span in before handle" + consumerSpan); } if (message instanceof ErrorMessage) { return new ErrorMessage((Throwable) message.getPayload(), headers.getMessageHeaders()); } headers.setImmutable(); return new GenericMessage<>(message.getPayload(), headers.getMessageHeaders()); }
java
@Override public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) { if (emptyMessage(message)) { return message; } MessageHeaderAccessor headers = mutableHeaderAccessor(message); TraceContextOrSamplingFlags extracted = this.extractor.extract(headers); // Start and finish a consumer span as we will immediately process it. Span consumerSpan = this.tracer.nextSpan(extracted); if (!consumerSpan.isNoop()) { consumerSpan.kind(Span.Kind.CONSUMER).start(); consumerSpan.remoteServiceName(REMOTE_SERVICE_NAME); addTags(message, consumerSpan, channel); consumerSpan.finish(); } // create and scope a span for the message processor this.threadLocalSpan .next(TraceContextOrSamplingFlags.create(consumerSpan.context())) .name("handle").start(); // remove any trace headers, but don't re-inject as we are synchronously // processing the // message and can rely on scoping to access this span later. MessageHeaderPropagation.removeAnyTraceHeaders(headers, this.tracing.propagation().keys()); if (log.isDebugEnabled()) { log.debug("Created a new span in before handle" + consumerSpan); } if (message instanceof ErrorMessage) { return new ErrorMessage((Throwable) message.getPayload(), headers.getMessageHeaders()); } headers.setImmutable(); return new GenericMessage<>(message.getPayload(), headers.getMessageHeaders()); }
[ "@", "Override", "public", "Message", "<", "?", ">", "beforeHandle", "(", "Message", "<", "?", ">", "message", ",", "MessageChannel", "channel", ",", "MessageHandler", "handler", ")", "{", "if", "(", "emptyMessage", "(", "message", ")", ")", "{", "return", "message", ";", "}", "MessageHeaderAccessor", "headers", "=", "mutableHeaderAccessor", "(", "message", ")", ";", "TraceContextOrSamplingFlags", "extracted", "=", "this", ".", "extractor", ".", "extract", "(", "headers", ")", ";", "// Start and finish a consumer span as we will immediately process it.", "Span", "consumerSpan", "=", "this", ".", "tracer", ".", "nextSpan", "(", "extracted", ")", ";", "if", "(", "!", "consumerSpan", ".", "isNoop", "(", ")", ")", "{", "consumerSpan", ".", "kind", "(", "Span", ".", "Kind", ".", "CONSUMER", ")", ".", "start", "(", ")", ";", "consumerSpan", ".", "remoteServiceName", "(", "REMOTE_SERVICE_NAME", ")", ";", "addTags", "(", "message", ",", "consumerSpan", ",", "channel", ")", ";", "consumerSpan", ".", "finish", "(", ")", ";", "}", "// create and scope a span for the message processor", "this", ".", "threadLocalSpan", ".", "next", "(", "TraceContextOrSamplingFlags", ".", "create", "(", "consumerSpan", ".", "context", "(", ")", ")", ")", ".", "name", "(", "\"handle\"", ")", ".", "start", "(", ")", ";", "// remove any trace headers, but don't re-inject as we are synchronously", "// processing the", "// message and can rely on scoping to access this span later.", "MessageHeaderPropagation", ".", "removeAnyTraceHeaders", "(", "headers", ",", "this", ".", "tracing", ".", "propagation", "(", ")", ".", "keys", "(", ")", ")", ";", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Created a new span in before handle\"", "+", "consumerSpan", ")", ";", "}", "if", "(", "message", "instanceof", "ErrorMessage", ")", "{", "return", "new", "ErrorMessage", "(", "(", "Throwable", ")", "message", ".", "getPayload", "(", ")", ",", "headers", ".", "getMessageHeaders", "(", ")", ")", ";", "}", "headers", ".", "setImmutable", "(", ")", ";", "return", "new", "GenericMessage", "<>", "(", "message", ".", "getPayload", "(", ")", ",", "headers", ".", "getMessageHeaders", "(", ")", ")", ";", "}" ]
This starts a consumer span as a child of the incoming message or the current trace context. It then creates a span for the handler, placing it in scope.
[ "This", "starts", "a", "consumer", "span", "as", "a", "child", "of", "the", "incoming", "message", "or", "the", "current", "trace", "context", ".", "It", "then", "creates", "a", "span", "for", "the", "handler", "placing", "it", "in", "scope", "." ]
f29c05fb8fba33e23aa21bb13aeb13ab8d27b485
https://github.com/spring-cloud/spring-cloud-sleuth/blob/f29c05fb8fba33e23aa21bb13aeb13ab8d27b485/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/messaging/TracingChannelInterceptor.java#L298-L332
19,263
spring-cloud/spring-cloud-sleuth
spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/messaging/TracingChannelInterceptor.java
TracingChannelInterceptor.addTags
void addTags(Message<?> message, SpanCustomizer result, MessageChannel channel) { // TODO topic etc if (channel != null) { result.tag("channel", messageChannelName(channel)); } }
java
void addTags(Message<?> message, SpanCustomizer result, MessageChannel channel) { // TODO topic etc if (channel != null) { result.tag("channel", messageChannelName(channel)); } }
[ "void", "addTags", "(", "Message", "<", "?", ">", "message", ",", "SpanCustomizer", "result", ",", "MessageChannel", "channel", ")", "{", "// TODO topic etc", "if", "(", "channel", "!=", "null", ")", "{", "result", ".", "tag", "(", "\"channel\"", ",", "messageChannelName", "(", "channel", ")", ")", ";", "}", "}" ]
When an upstream context was not present, lookup keys are unlikely added. @param message a message to append tags to @param result span to customize @param channel channel to which a message was sent
[ "When", "an", "upstream", "context", "was", "not", "present", "lookup", "keys", "are", "unlikely", "added", "." ]
f29c05fb8fba33e23aa21bb13aeb13ab8d27b485
https://github.com/spring-cloud/spring-cloud-sleuth/blob/f29c05fb8fba33e23aa21bb13aeb13ab8d27b485/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/messaging/TracingChannelInterceptor.java#L353-L358
19,264
spring-cloud/spring-cloud-sleuth
spring-cloud-sleuth-zipkin/src/main/java/org/springframework/cloud/sleuth/zipkin2/sender/RestTemplateSender.java
RestTemplateSender.check
@Override public CheckResult check() { try { post(new byte[] { '[', ']' }); return CheckResult.OK; } catch (Exception e) { return CheckResult.failed(e); } }
java
@Override public CheckResult check() { try { post(new byte[] { '[', ']' }); return CheckResult.OK; } catch (Exception e) { return CheckResult.failed(e); } }
[ "@", "Override", "public", "CheckResult", "check", "(", ")", "{", "try", "{", "post", "(", "new", "byte", "[", "]", "{", "'", "'", ",", "'", "'", "}", ")", ";", "return", "CheckResult", ".", "OK", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "CheckResult", ".", "failed", "(", "e", ")", ";", "}", "}" ]
Sends an empty json message to the configured endpoint.
[ "Sends", "an", "empty", "json", "message", "to", "the", "configured", "endpoint", "." ]
f29c05fb8fba33e23aa21bb13aeb13ab8d27b485
https://github.com/spring-cloud/spring-cloud-sleuth/blob/f29c05fb8fba33e23aa21bb13aeb13ab8d27b485/spring-cloud-sleuth-zipkin/src/main/java/org/springframework/cloud/sleuth/zipkin2/sender/RestTemplateSender.java#L108-L117
19,265
tipsy/javalin
src/main/java/io/javalin/Javalin.java
Javalin.start
public Javalin start() { Util.logJavalinBanner(this.config.showJavalinBanner); JettyUtil.disableJettyLogger(); long startupTimer = System.currentTimeMillis(); if (server.getStarted()) { throw new IllegalStateException("Cannot call start() again on a started server."); } server.setStarted(true); Util.printHelpfulMessageIfLoggerIsMissing(); eventManager.fireEvent(JavalinEvent.SERVER_STARTING); try { log.info("Starting Javalin ..."); server.start(servlet, wsServlet); log.info("Javalin started in " + (System.currentTimeMillis() - startupTimer) + "ms \\o/"); eventManager.fireEvent(JavalinEvent.SERVER_STARTED); } catch (Exception e) { log.error("Failed to start Javalin"); eventManager.fireEvent(JavalinEvent.SERVER_START_FAILED); if (Boolean.TRUE.equals(server.server().getAttribute("is-default-server"))) { stop();// stop if server is default server; otherwise, the caller is responsible to stop } if (e.getMessage() != null && e.getMessage().contains("Failed to bind to")) { throw new RuntimeException("Port already in use. Make sure no other process is using port " + server.getServerPort() + " and try again.", e); } else if (e.getMessage() != null && e.getMessage().contains("Permission denied")) { throw new RuntimeException("Port 1-1023 require elevated privileges (process must be started by admin).", e); } throw new RuntimeException(e); } return this; }
java
public Javalin start() { Util.logJavalinBanner(this.config.showJavalinBanner); JettyUtil.disableJettyLogger(); long startupTimer = System.currentTimeMillis(); if (server.getStarted()) { throw new IllegalStateException("Cannot call start() again on a started server."); } server.setStarted(true); Util.printHelpfulMessageIfLoggerIsMissing(); eventManager.fireEvent(JavalinEvent.SERVER_STARTING); try { log.info("Starting Javalin ..."); server.start(servlet, wsServlet); log.info("Javalin started in " + (System.currentTimeMillis() - startupTimer) + "ms \\o/"); eventManager.fireEvent(JavalinEvent.SERVER_STARTED); } catch (Exception e) { log.error("Failed to start Javalin"); eventManager.fireEvent(JavalinEvent.SERVER_START_FAILED); if (Boolean.TRUE.equals(server.server().getAttribute("is-default-server"))) { stop();// stop if server is default server; otherwise, the caller is responsible to stop } if (e.getMessage() != null && e.getMessage().contains("Failed to bind to")) { throw new RuntimeException("Port already in use. Make sure no other process is using port " + server.getServerPort() + " and try again.", e); } else if (e.getMessage() != null && e.getMessage().contains("Permission denied")) { throw new RuntimeException("Port 1-1023 require elevated privileges (process must be started by admin).", e); } throw new RuntimeException(e); } return this; }
[ "public", "Javalin", "start", "(", ")", "{", "Util", ".", "logJavalinBanner", "(", "this", ".", "config", ".", "showJavalinBanner", ")", ";", "JettyUtil", ".", "disableJettyLogger", "(", ")", ";", "long", "startupTimer", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "server", ".", "getStarted", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cannot call start() again on a started server.\"", ")", ";", "}", "server", ".", "setStarted", "(", "true", ")", ";", "Util", ".", "printHelpfulMessageIfLoggerIsMissing", "(", ")", ";", "eventManager", ".", "fireEvent", "(", "JavalinEvent", ".", "SERVER_STARTING", ")", ";", "try", "{", "log", ".", "info", "(", "\"Starting Javalin ...\"", ")", ";", "server", ".", "start", "(", "servlet", ",", "wsServlet", ")", ";", "log", ".", "info", "(", "\"Javalin started in \"", "+", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "startupTimer", ")", "+", "\"ms \\\\o/\"", ")", ";", "eventManager", ".", "fireEvent", "(", "JavalinEvent", ".", "SERVER_STARTED", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"Failed to start Javalin\"", ")", ";", "eventManager", ".", "fireEvent", "(", "JavalinEvent", ".", "SERVER_START_FAILED", ")", ";", "if", "(", "Boolean", ".", "TRUE", ".", "equals", "(", "server", ".", "server", "(", ")", ".", "getAttribute", "(", "\"is-default-server\"", ")", ")", ")", "{", "stop", "(", ")", ";", "// stop if server is default server; otherwise, the caller is responsible to stop", "}", "if", "(", "e", ".", "getMessage", "(", ")", "!=", "null", "&&", "e", ".", "getMessage", "(", ")", ".", "contains", "(", "\"Failed to bind to\"", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Port already in use. Make sure no other process is using port \"", "+", "server", ".", "getServerPort", "(", ")", "+", "\" and try again.\"", ",", "e", ")", ";", "}", "else", "if", "(", "e", ".", "getMessage", "(", ")", "!=", "null", "&&", "e", ".", "getMessage", "(", ")", ".", "contains", "(", "\"Permission denied\"", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Port 1-1023 require elevated privileges (process must be started by admin).\"", ",", "e", ")", ";", "}", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "return", "this", ";", "}" ]
Synchronously starts the application instance. @return running application instance. @see Javalin#create()
[ "Synchronously", "starts", "the", "application", "instance", "." ]
68b2f7592f237db1c2b597e645697eb75fdaee53
https://github.com/tipsy/javalin/blob/68b2f7592f237db1c2b597e645697eb75fdaee53/src/main/java/io/javalin/Javalin.java#L128-L157
19,266
tipsy/javalin
src/main/java/io/javalin/Javalin.java
Javalin.stop
public Javalin stop() { eventManager.fireEvent(JavalinEvent.SERVER_STOPPING); log.info("Stopping Javalin ..."); try { server.server().stop(); } catch (Exception e) { log.error("Javalin failed to stop gracefully", e); } log.info("Javalin has stopped"); eventManager.fireEvent(JavalinEvent.SERVER_STOPPED); return this; }
java
public Javalin stop() { eventManager.fireEvent(JavalinEvent.SERVER_STOPPING); log.info("Stopping Javalin ..."); try { server.server().stop(); } catch (Exception e) { log.error("Javalin failed to stop gracefully", e); } log.info("Javalin has stopped"); eventManager.fireEvent(JavalinEvent.SERVER_STOPPED); return this; }
[ "public", "Javalin", "stop", "(", ")", "{", "eventManager", ".", "fireEvent", "(", "JavalinEvent", ".", "SERVER_STOPPING", ")", ";", "log", ".", "info", "(", "\"Stopping Javalin ...\"", ")", ";", "try", "{", "server", ".", "server", "(", ")", ".", "stop", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"Javalin failed to stop gracefully\"", ",", "e", ")", ";", "}", "log", ".", "info", "(", "\"Javalin has stopped\"", ")", ";", "eventManager", ".", "fireEvent", "(", "JavalinEvent", ".", "SERVER_STOPPED", ")", ";", "return", "this", ";", "}" ]
Synchronously stops the application instance. @return stopped application instance.
[ "Synchronously", "stops", "the", "application", "instance", "." ]
68b2f7592f237db1c2b597e645697eb75fdaee53
https://github.com/tipsy/javalin/blob/68b2f7592f237db1c2b597e645697eb75fdaee53/src/main/java/io/javalin/Javalin.java#L164-L175
19,267
ACRA/acra
acra-core/src/main/java/org/acra/legacy/ReportMigrator.java
ReportMigrator.getCrashReportFiles
@NonNull private File[] getCrashReportFiles() { final File dir = context.getFilesDir(); if (dir == null) { ACRA.log.w(LOG_TAG, "Application files directory does not exist! The application may not be installed correctly. Please try reinstalling."); return new File[0]; } if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "Looking for error files in " + dir.getAbsolutePath()); // Filter for ".stacktrace" files final FilenameFilter filter = (dir1, name) -> name.endsWith(ACRAConstants.REPORTFILE_EXTENSION); final File[] result = dir.listFiles(filter); return (result == null) ? new File[0] : result; }
java
@NonNull private File[] getCrashReportFiles() { final File dir = context.getFilesDir(); if (dir == null) { ACRA.log.w(LOG_TAG, "Application files directory does not exist! The application may not be installed correctly. Please try reinstalling."); return new File[0]; } if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "Looking for error files in " + dir.getAbsolutePath()); // Filter for ".stacktrace" files final FilenameFilter filter = (dir1, name) -> name.endsWith(ACRAConstants.REPORTFILE_EXTENSION); final File[] result = dir.listFiles(filter); return (result == null) ? new File[0] : result; }
[ "@", "NonNull", "private", "File", "[", "]", "getCrashReportFiles", "(", ")", "{", "final", "File", "dir", "=", "context", ".", "getFilesDir", "(", ")", ";", "if", "(", "dir", "==", "null", ")", "{", "ACRA", ".", "log", ".", "w", "(", "LOG_TAG", ",", "\"Application files directory does not exist! The application may not be installed correctly. Please try reinstalling.\"", ")", ";", "return", "new", "File", "[", "0", "]", ";", "}", "if", "(", "ACRA", ".", "DEV_LOGGING", ")", "ACRA", ".", "log", ".", "d", "(", "LOG_TAG", ",", "\"Looking for error files in \"", "+", "dir", ".", "getAbsolutePath", "(", ")", ")", ";", "// Filter for \".stacktrace\" files", "final", "FilenameFilter", "filter", "=", "(", "dir1", ",", "name", ")", "->", "name", ".", "endsWith", "(", "ACRAConstants", ".", "REPORTFILE_EXTENSION", ")", ";", "final", "File", "[", "]", "result", "=", "dir", ".", "listFiles", "(", "filter", ")", ";", "return", "(", "result", "==", "null", ")", "?", "new", "File", "[", "0", "]", ":", "result", ";", "}" ]
Returns an array containing the names of pending crash report files. @return an array containing the names of pending crash report files.
[ "Returns", "an", "array", "containing", "the", "names", "of", "pending", "crash", "report", "files", "." ]
bfa3235ab110328c5ab2f792ddf8ee87be4a32d1
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/legacy/ReportMigrator.java#L72-L86
19,268
ACRA/acra
acra-core/src/main/java/org/acra/builder/LastActivityManager.java
LastActivityManager.waitForAllActivitiesDestroy
public void waitForAllActivitiesDestroy(int timeOutInMillis) { synchronized (activityStack) { long start = System.currentTimeMillis(); long now = start; while (!activityStack.isEmpty() && start + timeOutInMillis > now) { try { activityStack.wait(start - now + timeOutInMillis); } catch (InterruptedException ignored) { } now = System.currentTimeMillis(); } } }
java
public void waitForAllActivitiesDestroy(int timeOutInMillis) { synchronized (activityStack) { long start = System.currentTimeMillis(); long now = start; while (!activityStack.isEmpty() && start + timeOutInMillis > now) { try { activityStack.wait(start - now + timeOutInMillis); } catch (InterruptedException ignored) { } now = System.currentTimeMillis(); } } }
[ "public", "void", "waitForAllActivitiesDestroy", "(", "int", "timeOutInMillis", ")", "{", "synchronized", "(", "activityStack", ")", "{", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "now", "=", "start", ";", "while", "(", "!", "activityStack", ".", "isEmpty", "(", ")", "&&", "start", "+", "timeOutInMillis", ">", "now", ")", "{", "try", "{", "activityStack", ".", "wait", "(", "start", "-", "now", "+", "timeOutInMillis", ")", ";", "}", "catch", "(", "InterruptedException", "ignored", ")", "{", "}", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "}", "}", "}" ]
wait until the last activity is stopped @param timeOutInMillis timeout for wait
[ "wait", "until", "the", "last", "activity", "is", "stopped" ]
bfa3235ab110328c5ab2f792ddf8ee87be4a32d1
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/builder/LastActivityManager.java#L118-L130
19,269
ACRA/acra
acra-core/src/main/java/org/acra/sender/ReportDistributor.java
ReportDistributor.isDebuggable
private boolean isDebuggable() { final PackageManager pm = context.getPackageManager(); try { return (pm.getApplicationInfo(context.getPackageName(), 0).flags & ApplicationInfo.FLAG_DEBUGGABLE) > 0; } catch (PackageManager.NameNotFoundException e) { return false; } }
java
private boolean isDebuggable() { final PackageManager pm = context.getPackageManager(); try { return (pm.getApplicationInfo(context.getPackageName(), 0).flags & ApplicationInfo.FLAG_DEBUGGABLE) > 0; } catch (PackageManager.NameNotFoundException e) { return false; } }
[ "private", "boolean", "isDebuggable", "(", ")", "{", "final", "PackageManager", "pm", "=", "context", ".", "getPackageManager", "(", ")", ";", "try", "{", "return", "(", "pm", ".", "getApplicationInfo", "(", "context", ".", "getPackageName", "(", ")", ",", "0", ")", ".", "flags", "&", "ApplicationInfo", ".", "FLAG_DEBUGGABLE", ")", ">", "0", ";", "}", "catch", "(", "PackageManager", ".", "NameNotFoundException", "e", ")", "{", "return", "false", ";", "}", "}" ]
Returns true if the application is debuggable. @return true if the application is debuggable.
[ "Returns", "true", "if", "the", "application", "is", "debuggable", "." ]
bfa3235ab110328c5ab2f792ddf8ee87be4a32d1
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/sender/ReportDistributor.java#L141-L148
19,270
ACRA/acra
acra-core/src/main/java/org/acra/util/ApplicationStartupProcessor.java
ApplicationStartupProcessor.deleteUnsentReportsFromOldAppVersion
private void deleteUnsentReportsFromOldAppVersion() { final SharedPreferences prefs = new SharedPreferencesFactory(context, config).create(); final long lastVersionNr = prefs.getInt(ACRA.PREF_LAST_VERSION_NR, 0); final int appVersion = getAppVersion(); if (appVersion > lastVersionNr) { reportDeleter.deleteReports(true, 0); reportDeleter.deleteReports(false, 0); prefs.edit().putInt(ACRA.PREF_LAST_VERSION_NR, appVersion).apply(); } }
java
private void deleteUnsentReportsFromOldAppVersion() { final SharedPreferences prefs = new SharedPreferencesFactory(context, config).create(); final long lastVersionNr = prefs.getInt(ACRA.PREF_LAST_VERSION_NR, 0); final int appVersion = getAppVersion(); if (appVersion > lastVersionNr) { reportDeleter.deleteReports(true, 0); reportDeleter.deleteReports(false, 0); prefs.edit().putInt(ACRA.PREF_LAST_VERSION_NR, appVersion).apply(); } }
[ "private", "void", "deleteUnsentReportsFromOldAppVersion", "(", ")", "{", "final", "SharedPreferences", "prefs", "=", "new", "SharedPreferencesFactory", "(", "context", ",", "config", ")", ".", "create", "(", ")", ";", "final", "long", "lastVersionNr", "=", "prefs", ".", "getInt", "(", "ACRA", ".", "PREF_LAST_VERSION_NR", ",", "0", ")", ";", "final", "int", "appVersion", "=", "getAppVersion", "(", ")", ";", "if", "(", "appVersion", ">", "lastVersionNr", ")", "{", "reportDeleter", ".", "deleteReports", "(", "true", ",", "0", ")", ";", "reportDeleter", ".", "deleteReports", "(", "false", ",", "0", ")", ";", "prefs", ".", "edit", "(", ")", ".", "putInt", "(", "ACRA", ".", "PREF_LAST_VERSION_NR", ",", "appVersion", ")", ".", "apply", "(", ")", ";", "}", "}" ]
Delete any old unsent reports if this is a newer version of the app than when we last started.
[ "Delete", "any", "old", "unsent", "reports", "if", "this", "is", "a", "newer", "version", "of", "the", "app", "than", "when", "we", "last", "started", "." ]
bfa3235ab110328c5ab2f792ddf8ee87be4a32d1
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/util/ApplicationStartupProcessor.java#L56-L67
19,271
ACRA/acra
acra-core/src/main/java/org/acra/data/CrashReportDataFactory.java
CrashReportDataFactory.createCrashData
@NonNull public CrashReportData createCrashData(@NonNull final ReportBuilder builder) { final ExecutorService executorService = config.parallel() ? Executors.newCachedThreadPool() : Executors.newSingleThreadExecutor(); final CrashReportData crashReportData = new CrashReportData(); final List<Future<?>> futures = new ArrayList<>(); for (final Collector collector : collectors) { futures.add(executorService.submit(() -> { //catch absolutely everything possible here so no collector obstructs the others try { if(ACRA.DEV_LOGGING)ACRA.log.d(LOG_TAG, "Calling collector " + collector.getClass().getName()); collector.collect(context, config, builder, crashReportData); if(ACRA.DEV_LOGGING)ACRA.log.d(LOG_TAG, "Collector " + collector.getClass().getName() + " completed"); }catch (CollectorException e){ ACRA.log.w(LOG_TAG, e); }catch (Exception t) { ACRA.log.e(LOG_TAG, "Error in collector " + collector.getClass().getSimpleName(), t); } })); } for (Future<?> future : futures) { while (!future.isDone()) { try { future.get(); } catch (InterruptedException ignored) { } catch (ExecutionException e) { break; } } } return crashReportData; }
java
@NonNull public CrashReportData createCrashData(@NonNull final ReportBuilder builder) { final ExecutorService executorService = config.parallel() ? Executors.newCachedThreadPool() : Executors.newSingleThreadExecutor(); final CrashReportData crashReportData = new CrashReportData(); final List<Future<?>> futures = new ArrayList<>(); for (final Collector collector : collectors) { futures.add(executorService.submit(() -> { //catch absolutely everything possible here so no collector obstructs the others try { if(ACRA.DEV_LOGGING)ACRA.log.d(LOG_TAG, "Calling collector " + collector.getClass().getName()); collector.collect(context, config, builder, crashReportData); if(ACRA.DEV_LOGGING)ACRA.log.d(LOG_TAG, "Collector " + collector.getClass().getName() + " completed"); }catch (CollectorException e){ ACRA.log.w(LOG_TAG, e); }catch (Exception t) { ACRA.log.e(LOG_TAG, "Error in collector " + collector.getClass().getSimpleName(), t); } })); } for (Future<?> future : futures) { while (!future.isDone()) { try { future.get(); } catch (InterruptedException ignored) { } catch (ExecutionException e) { break; } } } return crashReportData; }
[ "@", "NonNull", "public", "CrashReportData", "createCrashData", "(", "@", "NonNull", "final", "ReportBuilder", "builder", ")", "{", "final", "ExecutorService", "executorService", "=", "config", ".", "parallel", "(", ")", "?", "Executors", ".", "newCachedThreadPool", "(", ")", ":", "Executors", ".", "newSingleThreadExecutor", "(", ")", ";", "final", "CrashReportData", "crashReportData", "=", "new", "CrashReportData", "(", ")", ";", "final", "List", "<", "Future", "<", "?", ">", ">", "futures", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "final", "Collector", "collector", ":", "collectors", ")", "{", "futures", ".", "add", "(", "executorService", ".", "submit", "(", "(", ")", "->", "{", "//catch absolutely everything possible here so no collector obstructs the others", "try", "{", "if", "(", "ACRA", ".", "DEV_LOGGING", ")", "ACRA", ".", "log", ".", "d", "(", "LOG_TAG", ",", "\"Calling collector \"", "+", "collector", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "collector", ".", "collect", "(", "context", ",", "config", ",", "builder", ",", "crashReportData", ")", ";", "if", "(", "ACRA", ".", "DEV_LOGGING", ")", "ACRA", ".", "log", ".", "d", "(", "LOG_TAG", ",", "\"Collector \"", "+", "collector", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\" completed\"", ")", ";", "}", "catch", "(", "CollectorException", "e", ")", "{", "ACRA", ".", "log", ".", "w", "(", "LOG_TAG", ",", "e", ")", ";", "}", "catch", "(", "Exception", "t", ")", "{", "ACRA", ".", "log", ".", "e", "(", "LOG_TAG", ",", "\"Error in collector \"", "+", "collector", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ",", "t", ")", ";", "}", "}", ")", ")", ";", "}", "for", "(", "Future", "<", "?", ">", "future", ":", "futures", ")", "{", "while", "(", "!", "future", ".", "isDone", "(", ")", ")", "{", "try", "{", "future", ".", "get", "(", ")", ";", "}", "catch", "(", "InterruptedException", "ignored", ")", "{", "}", "catch", "(", "ExecutionException", "e", ")", "{", "break", ";", "}", "}", "}", "return", "crashReportData", ";", "}" ]
Collects crash data. @param builder ReportBuilder for whom to crete the crash report. @return CrashReportData identifying the current crash.
[ "Collects", "crash", "data", "." ]
bfa3235ab110328c5ab2f792ddf8ee87be4a32d1
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/data/CrashReportDataFactory.java#L78-L108
19,272
ACRA/acra
acra-core/src/main/java/org/acra/collector/MemoryInfoCollector.java
MemoryInfoCollector.getAvailableInternalMemorySize
private long getAvailableInternalMemorySize() { final File path = Environment.getDataDirectory(); final StatFs stat = new StatFs(path.getPath()); final long blockSize; final long availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); availableBlocks = stat.getAvailableBlocksLong(); } else { //noinspection deprecation blockSize = stat.getBlockSize(); //noinspection deprecation availableBlocks = stat.getAvailableBlocks(); } return availableBlocks * blockSize; }
java
private long getAvailableInternalMemorySize() { final File path = Environment.getDataDirectory(); final StatFs stat = new StatFs(path.getPath()); final long blockSize; final long availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); availableBlocks = stat.getAvailableBlocksLong(); } else { //noinspection deprecation blockSize = stat.getBlockSize(); //noinspection deprecation availableBlocks = stat.getAvailableBlocks(); } return availableBlocks * blockSize; }
[ "private", "long", "getAvailableInternalMemorySize", "(", ")", "{", "final", "File", "path", "=", "Environment", ".", "getDataDirectory", "(", ")", ";", "final", "StatFs", "stat", "=", "new", "StatFs", "(", "path", ".", "getPath", "(", ")", ")", ";", "final", "long", "blockSize", ";", "final", "long", "availableBlocks", ";", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "Build", ".", "VERSION_CODES", ".", "JELLY_BEAN_MR2", ")", "{", "blockSize", "=", "stat", ".", "getBlockSizeLong", "(", ")", ";", "availableBlocks", "=", "stat", ".", "getAvailableBlocksLong", "(", ")", ";", "}", "else", "{", "//noinspection deprecation", "blockSize", "=", "stat", ".", "getBlockSize", "(", ")", ";", "//noinspection deprecation", "availableBlocks", "=", "stat", ".", "getAvailableBlocks", "(", ")", ";", "}", "return", "availableBlocks", "*", "blockSize", ";", "}" ]
Calculates the free memory of the device. This is based on an inspection of the filesystem, which in android devices is stored in RAM. @return Number of bytes available.
[ "Calculates", "the", "free", "memory", "of", "the", "device", ".", "This", "is", "based", "on", "an", "inspection", "of", "the", "filesystem", "which", "in", "android", "devices", "is", "stored", "in", "RAM", "." ]
bfa3235ab110328c5ab2f792ddf8ee87be4a32d1
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/collector/MemoryInfoCollector.java#L102-L117
19,273
ACRA/acra
acra-core/src/main/java/org/acra/collector/MemoryInfoCollector.java
MemoryInfoCollector.getTotalInternalMemorySize
private long getTotalInternalMemorySize() { final File path = Environment.getDataDirectory(); final StatFs stat = new StatFs(path.getPath()); final long blockSize; final long totalBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); totalBlocks = stat.getBlockCountLong(); } else { //noinspection deprecation blockSize = stat.getBlockSize(); //noinspection deprecation totalBlocks = stat.getBlockCount(); } return totalBlocks * blockSize; }
java
private long getTotalInternalMemorySize() { final File path = Environment.getDataDirectory(); final StatFs stat = new StatFs(path.getPath()); final long blockSize; final long totalBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); totalBlocks = stat.getBlockCountLong(); } else { //noinspection deprecation blockSize = stat.getBlockSize(); //noinspection deprecation totalBlocks = stat.getBlockCount(); } return totalBlocks * blockSize; }
[ "private", "long", "getTotalInternalMemorySize", "(", ")", "{", "final", "File", "path", "=", "Environment", ".", "getDataDirectory", "(", ")", ";", "final", "StatFs", "stat", "=", "new", "StatFs", "(", "path", ".", "getPath", "(", ")", ")", ";", "final", "long", "blockSize", ";", "final", "long", "totalBlocks", ";", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "Build", ".", "VERSION_CODES", ".", "JELLY_BEAN_MR2", ")", "{", "blockSize", "=", "stat", ".", "getBlockSizeLong", "(", ")", ";", "totalBlocks", "=", "stat", ".", "getBlockCountLong", "(", ")", ";", "}", "else", "{", "//noinspection deprecation", "blockSize", "=", "stat", ".", "getBlockSize", "(", ")", ";", "//noinspection deprecation", "totalBlocks", "=", "stat", ".", "getBlockCount", "(", ")", ";", "}", "return", "totalBlocks", "*", "blockSize", ";", "}" ]
Calculates the total memory of the device. This is based on an inspection of the filesystem, which in android devices is stored in RAM. @return Total number of bytes.
[ "Calculates", "the", "total", "memory", "of", "the", "device", ".", "This", "is", "based", "on", "an", "inspection", "of", "the", "filesystem", "which", "in", "android", "devices", "is", "stored", "in", "RAM", "." ]
bfa3235ab110328c5ab2f792ddf8ee87be4a32d1
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/collector/MemoryInfoCollector.java#L124-L139
19,274
ACRA/acra
acra-dialog/src/main/java/org/acra/dialog/CrashReportDialog.java
CrashReportDialog.getMainView
@NonNull protected View getMainView() { final TextView text = new TextView(this); final String dialogText = dialogConfiguration.text(); if (dialogText != null) { text.setText(dialogText); } return text; }
java
@NonNull protected View getMainView() { final TextView text = new TextView(this); final String dialogText = dialogConfiguration.text(); if (dialogText != null) { text.setText(dialogText); } return text; }
[ "@", "NonNull", "protected", "View", "getMainView", "(", ")", "{", "final", "TextView", "text", "=", "new", "TextView", "(", "this", ")", ";", "final", "String", "dialogText", "=", "dialogConfiguration", ".", "text", "(", ")", ";", "if", "(", "dialogText", "!=", "null", ")", "{", "text", ".", "setText", "(", "dialogText", ")", ";", "}", "return", "text", ";", "}" ]
Creates a main view containing text of resText, or nothing if not found @return the main view
[ "Creates", "a", "main", "view", "containing", "text", "of", "resText", "or", "nothing", "if", "not", "found" ]
bfa3235ab110328c5ab2f792ddf8ee87be4a32d1
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-dialog/src/main/java/org/acra/dialog/CrashReportDialog.java#L152-L160
19,275
ACRA/acra
acra-dialog/src/main/java/org/acra/dialog/CrashReportDialog.java
CrashReportDialog.getCommentLabel
@Nullable protected View getCommentLabel() { final String commentPrompt = dialogConfiguration.commentPrompt(); if (commentPrompt != null) { final TextView labelView = new TextView(this); labelView.setText(commentPrompt); return labelView; } return null; }
java
@Nullable protected View getCommentLabel() { final String commentPrompt = dialogConfiguration.commentPrompt(); if (commentPrompt != null) { final TextView labelView = new TextView(this); labelView.setText(commentPrompt); return labelView; } return null; }
[ "@", "Nullable", "protected", "View", "getCommentLabel", "(", ")", "{", "final", "String", "commentPrompt", "=", "dialogConfiguration", ".", "commentPrompt", "(", ")", ";", "if", "(", "commentPrompt", "!=", "null", ")", "{", "final", "TextView", "labelView", "=", "new", "TextView", "(", "this", ")", ";", "labelView", ".", "setText", "(", "commentPrompt", ")", ";", "return", "labelView", ";", "}", "return", "null", ";", "}" ]
creates a comment label view with resCommentPrompt as text @return the label or null if there is no resource
[ "creates", "a", "comment", "label", "view", "with", "resCommentPrompt", "as", "text" ]
bfa3235ab110328c5ab2f792ddf8ee87be4a32d1
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-dialog/src/main/java/org/acra/dialog/CrashReportDialog.java#L167-L176
19,276
ACRA/acra
acra-dialog/src/main/java/org/acra/dialog/CrashReportDialog.java
CrashReportDialog.getEmailLabel
@Nullable protected View getEmailLabel() { final String emailPrompt = dialogConfiguration.emailPrompt(); if (emailPrompt != null) { final TextView labelView = new TextView(this); labelView.setText(emailPrompt); return labelView; } return null; }
java
@Nullable protected View getEmailLabel() { final String emailPrompt = dialogConfiguration.emailPrompt(); if (emailPrompt != null) { final TextView labelView = new TextView(this); labelView.setText(emailPrompt); return labelView; } return null; }
[ "@", "Nullable", "protected", "View", "getEmailLabel", "(", ")", "{", "final", "String", "emailPrompt", "=", "dialogConfiguration", ".", "emailPrompt", "(", ")", ";", "if", "(", "emailPrompt", "!=", "null", ")", "{", "final", "TextView", "labelView", "=", "new", "TextView", "(", "this", ")", ";", "labelView", ".", "setText", "(", "emailPrompt", ")", ";", "return", "labelView", ";", "}", "return", "null", ";", "}" ]
creates a email label view with resEmailPrompt as text @return the label or null if there is no resource
[ "creates", "a", "email", "label", "view", "with", "resEmailPrompt", "as", "text" ]
bfa3235ab110328c5ab2f792ddf8ee87be4a32d1
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-dialog/src/main/java/org/acra/dialog/CrashReportDialog.java#L199-L208
19,277
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.getCalendarContentDescription
public CharSequence getCalendarContentDescription() { return calendarContentDescription != null ? calendarContentDescription : getContext().getString(R.string.calendar); }
java
public CharSequence getCalendarContentDescription() { return calendarContentDescription != null ? calendarContentDescription : getContext().getString(R.string.calendar); }
[ "public", "CharSequence", "getCalendarContentDescription", "(", ")", "{", "return", "calendarContentDescription", "!=", "null", "?", "calendarContentDescription", ":", "getContext", "(", ")", ".", "getString", "(", "R", ".", "string", ".", "calendar", ")", ";", "}" ]
Get content description for calendar @return calendar's content description
[ "Get", "content", "description", "for", "calendar" ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L689-L693
19,278
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.getSelectedDate
@Nullable public CalendarDay getSelectedDate() { List<CalendarDay> dates = adapter.getSelectedDates(); if (dates.isEmpty()) { return null; } else { return dates.get(dates.size() - 1); } }
java
@Nullable public CalendarDay getSelectedDate() { List<CalendarDay> dates = adapter.getSelectedDates(); if (dates.isEmpty()) { return null; } else { return dates.get(dates.size() - 1); } }
[ "@", "Nullable", "public", "CalendarDay", "getSelectedDate", "(", ")", "{", "List", "<", "CalendarDay", ">", "dates", "=", "adapter", ".", "getSelectedDates", "(", ")", ";", "if", "(", "dates", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "dates", ".", "get", "(", "dates", ".", "size", "(", ")", "-", "1", ")", ";", "}", "}" ]
Get the currently selected date, or null if no selection. Depending on the selection mode, you might get different results. <p>For {@link #SELECTION_MODE_SINGLE}, returns the selected date.</p> <p>For {@link #SELECTION_MODE_MULTIPLE}, returns the last date selected.</p> <p>For {@link #SELECTION_MODE_RANGE}, returns the last date of the range. In most cases, you should probably be using {@link #getSelectedDates()}.</p> <p>For {@link #SELECTION_MODE_NONE}, returns null.</p> @return The selected day, or null if no selection. If in multiple selection mode, this will return the last date of the list of selected dates. @see MaterialCalendarView#getSelectedDates()
[ "Get", "the", "currently", "selected", "date", "or", "null", "if", "no", "selection", ".", "Depending", "on", "the", "selection", "mode", "you", "might", "get", "different", "results", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L767-L774
19,279
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.setWeekDayFormatter
public void setWeekDayFormatter(WeekDayFormatter formatter) { adapter.setWeekDayFormatter(formatter == null ? WeekDayFormatter.DEFAULT : formatter); }
java
public void setWeekDayFormatter(WeekDayFormatter formatter) { adapter.setWeekDayFormatter(formatter == null ? WeekDayFormatter.DEFAULT : formatter); }
[ "public", "void", "setWeekDayFormatter", "(", "WeekDayFormatter", "formatter", ")", "{", "adapter", ".", "setWeekDayFormatter", "(", "formatter", "==", "null", "?", "WeekDayFormatter", ".", "DEFAULT", ":", "formatter", ")", ";", "}" ]
Set a formatter for weekday labels. @param formatter the new formatter, null for default
[ "Set", "a", "formatter", "for", "weekday", "labels", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L937-L939
19,280
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.setDayFormatter
public void setDayFormatter(DayFormatter formatter) { adapter.setDayFormatter(formatter == null ? DayFormatter.DEFAULT : formatter); }
java
public void setDayFormatter(DayFormatter formatter) { adapter.setDayFormatter(formatter == null ? DayFormatter.DEFAULT : formatter); }
[ "public", "void", "setDayFormatter", "(", "DayFormatter", "formatter", ")", "{", "adapter", ".", "setDayFormatter", "(", "formatter", "==", "null", "?", "DayFormatter", ".", "DEFAULT", ":", "formatter", ")", ";", "}" ]
Set a formatter for day labels. @param formatter the new formatter, null for default
[ "Set", "a", "formatter", "for", "day", "labels", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L946-L948
19,281
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.addDecorators
public void addDecorators(Collection<? extends DayViewDecorator> decorators) { if (decorators == null) { return; } dayViewDecorators.addAll(decorators); adapter.setDecorators(dayViewDecorators); }
java
public void addDecorators(Collection<? extends DayViewDecorator> decorators) { if (decorators == null) { return; } dayViewDecorators.addAll(decorators); adapter.setDecorators(dayViewDecorators); }
[ "public", "void", "addDecorators", "(", "Collection", "<", "?", "extends", "DayViewDecorator", ">", "decorators", ")", "{", "if", "(", "decorators", "==", "null", ")", "{", "return", ";", "}", "dayViewDecorators", ".", "addAll", "(", "decorators", ")", ";", "adapter", ".", "setDecorators", "(", "dayViewDecorators", ")", ";", "}" ]
Add a collection of day decorators @param decorators decorators to add
[ "Add", "a", "collection", "of", "day", "decorators" ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L1250-L1257
19,282
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.addDecorator
public void addDecorator(DayViewDecorator decorator) { if (decorator == null) { return; } dayViewDecorators.add(decorator); adapter.setDecorators(dayViewDecorators); }
java
public void addDecorator(DayViewDecorator decorator) { if (decorator == null) { return; } dayViewDecorators.add(decorator); adapter.setDecorators(dayViewDecorators); }
[ "public", "void", "addDecorator", "(", "DayViewDecorator", "decorator", ")", "{", "if", "(", "decorator", "==", "null", ")", "{", "return", ";", "}", "dayViewDecorators", ".", "add", "(", "decorator", ")", ";", "adapter", ".", "setDecorators", "(", "dayViewDecorators", ")", ";", "}" ]
Add a day decorator @param decorator decorator to add
[ "Add", "a", "day", "decorator" ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L1273-L1279
19,283
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.dispatchOnDateSelected
protected void dispatchOnDateSelected(final CalendarDay day, final boolean selected) { if (listener != null) { listener.onDateSelected(MaterialCalendarView.this, day, selected); } }
java
protected void dispatchOnDateSelected(final CalendarDay day, final boolean selected) { if (listener != null) { listener.onDateSelected(MaterialCalendarView.this, day, selected); } }
[ "protected", "void", "dispatchOnDateSelected", "(", "final", "CalendarDay", "day", ",", "final", "boolean", "selected", ")", "{", "if", "(", "listener", "!=", "null", ")", "{", "listener", ".", "onDateSelected", "(", "MaterialCalendarView", ".", "this", ",", "day", ",", "selected", ")", ";", "}", "}" ]
Dispatch date change events to a listener, if set @param day the day that was selected @param selected true if the day is now currently selected, false otherwise
[ "Dispatch", "date", "change", "events", "to", "a", "listener", "if", "set" ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L1362-L1366
19,284
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.dispatchOnRangeSelected
protected void dispatchOnRangeSelected(@NonNull final List<CalendarDay> days) { if (rangeListener != null) { rangeListener.onRangeSelected(MaterialCalendarView.this, days); } }
java
protected void dispatchOnRangeSelected(@NonNull final List<CalendarDay> days) { if (rangeListener != null) { rangeListener.onRangeSelected(MaterialCalendarView.this, days); } }
[ "protected", "void", "dispatchOnRangeSelected", "(", "@", "NonNull", "final", "List", "<", "CalendarDay", ">", "days", ")", "{", "if", "(", "rangeListener", "!=", "null", ")", "{", "rangeListener", ".", "onRangeSelected", "(", "MaterialCalendarView", ".", "this", ",", "days", ")", ";", "}", "}" ]
Dispatch a range of days to a range listener, if set, ordered chronologically. @param days Enclosing days ordered from first to last day.
[ "Dispatch", "a", "range", "of", "days", "to", "a", "range", "listener", "if", "set", "ordered", "chronologically", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L1373-L1377
19,285
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.selectRange
public void selectRange(final CalendarDay firstDay, final CalendarDay lastDay) { if (firstDay == null || lastDay == null) { return; } else if (firstDay.isAfter(lastDay)) { adapter.selectRange(lastDay, firstDay); dispatchOnRangeSelected(adapter.getSelectedDates()); } else { adapter.selectRange(firstDay, lastDay); dispatchOnRangeSelected(adapter.getSelectedDates()); } }
java
public void selectRange(final CalendarDay firstDay, final CalendarDay lastDay) { if (firstDay == null || lastDay == null) { return; } else if (firstDay.isAfter(lastDay)) { adapter.selectRange(lastDay, firstDay); dispatchOnRangeSelected(adapter.getSelectedDates()); } else { adapter.selectRange(firstDay, lastDay); dispatchOnRangeSelected(adapter.getSelectedDates()); } }
[ "public", "void", "selectRange", "(", "final", "CalendarDay", "firstDay", ",", "final", "CalendarDay", "lastDay", ")", "{", "if", "(", "firstDay", "==", "null", "||", "lastDay", "==", "null", ")", "{", "return", ";", "}", "else", "if", "(", "firstDay", ".", "isAfter", "(", "lastDay", ")", ")", "{", "adapter", ".", "selectRange", "(", "lastDay", ",", "firstDay", ")", ";", "dispatchOnRangeSelected", "(", "adapter", ".", "getSelectedDates", "(", ")", ")", ";", "}", "else", "{", "adapter", ".", "selectRange", "(", "firstDay", ",", "lastDay", ")", ";", "dispatchOnRangeSelected", "(", "adapter", ".", "getSelectedDates", "(", ")", ")", ";", "}", "}" ]
Select a fresh range of date including first day and last day. @param firstDay first day of the range to select @param lastDay last day of the range to select
[ "Select", "a", "fresh", "range", "of", "date", "including", "first", "day", "and", "last", "day", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L1451-L1461
19,286
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.clampSize
private static int clampSize(int size, int spec) { int specMode = MeasureSpec.getMode(spec); int specSize = MeasureSpec.getSize(spec); switch (specMode) { case MeasureSpec.EXACTLY: { return specSize; } case MeasureSpec.AT_MOST: { return Math.min(size, specSize); } case MeasureSpec.UNSPECIFIED: default: { return size; } } }
java
private static int clampSize(int size, int spec) { int specMode = MeasureSpec.getMode(spec); int specSize = MeasureSpec.getSize(spec); switch (specMode) { case MeasureSpec.EXACTLY: { return specSize; } case MeasureSpec.AT_MOST: { return Math.min(size, specSize); } case MeasureSpec.UNSPECIFIED: default: { return size; } } }
[ "private", "static", "int", "clampSize", "(", "int", "size", ",", "int", "spec", ")", "{", "int", "specMode", "=", "MeasureSpec", ".", "getMode", "(", "spec", ")", ";", "int", "specSize", "=", "MeasureSpec", ".", "getSize", "(", "spec", ")", ";", "switch", "(", "specMode", ")", "{", "case", "MeasureSpec", ".", "EXACTLY", ":", "{", "return", "specSize", ";", "}", "case", "MeasureSpec", ".", "AT_MOST", ":", "{", "return", "Math", ".", "min", "(", "size", ",", "specSize", ")", ";", "}", "case", "MeasureSpec", ".", "UNSPECIFIED", ":", "default", ":", "{", "return", "size", ";", "}", "}", "}" ]
Clamp the size to the measure spec. @param size Size we want to be @param spec Measure spec to clamp against @return the appropriate size to pass to {@linkplain View#setMeasuredDimension(int, int)}
[ "Clamp", "the", "size", "to", "the", "measure", "spec", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L1664-L1679
19,287
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.enableView
private static void enableView(final View view, final boolean enable) { view.setEnabled(enable); view.setAlpha(enable ? 1f : 0.1f); }
java
private static void enableView(final View view, final boolean enable) { view.setEnabled(enable); view.setAlpha(enable ? 1f : 0.1f); }
[ "private", "static", "void", "enableView", "(", "final", "View", "view", ",", "final", "boolean", "enable", ")", "{", "view", ".", "setEnabled", "(", "enable", ")", ";", "view", ".", "setAlpha", "(", "enable", "?", "1f", ":", "0.1f", ")", ";", "}" ]
Used for enabling or disabling views, while also changing the alpha. @param view The view to enable or disable. @param enable Whether to enable or disable the view.
[ "Used", "for", "enabling", "or", "disabling", "views", "while", "also", "changing", "the", "alpha", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L2014-L2017
19,288
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java
DayView.setDayFormatter
public void setDayFormatter(DayFormatter formatter) { this.contentDescriptionFormatter = contentDescriptionFormatter == this.formatter ? formatter : contentDescriptionFormatter; this.formatter = formatter == null ? DayFormatter.DEFAULT : formatter; CharSequence currentLabel = getText(); Object[] spans = null; if (currentLabel instanceof Spanned) { spans = ((Spanned) currentLabel).getSpans(0, currentLabel.length(), Object.class); } SpannableString newLabel = new SpannableString(getLabel()); if (spans != null) { for (Object span : spans) { newLabel.setSpan(span, 0, newLabel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } setText(newLabel); }
java
public void setDayFormatter(DayFormatter formatter) { this.contentDescriptionFormatter = contentDescriptionFormatter == this.formatter ? formatter : contentDescriptionFormatter; this.formatter = formatter == null ? DayFormatter.DEFAULT : formatter; CharSequence currentLabel = getText(); Object[] spans = null; if (currentLabel instanceof Spanned) { spans = ((Spanned) currentLabel).getSpans(0, currentLabel.length(), Object.class); } SpannableString newLabel = new SpannableString(getLabel()); if (spans != null) { for (Object span : spans) { newLabel.setSpan(span, 0, newLabel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } setText(newLabel); }
[ "public", "void", "setDayFormatter", "(", "DayFormatter", "formatter", ")", "{", "this", ".", "contentDescriptionFormatter", "=", "contentDescriptionFormatter", "==", "this", ".", "formatter", "?", "formatter", ":", "contentDescriptionFormatter", ";", "this", ".", "formatter", "=", "formatter", "==", "null", "?", "DayFormatter", ".", "DEFAULT", ":", "formatter", ";", "CharSequence", "currentLabel", "=", "getText", "(", ")", ";", "Object", "[", "]", "spans", "=", "null", ";", "if", "(", "currentLabel", "instanceof", "Spanned", ")", "{", "spans", "=", "(", "(", "Spanned", ")", "currentLabel", ")", ".", "getSpans", "(", "0", ",", "currentLabel", ".", "length", "(", ")", ",", "Object", ".", "class", ")", ";", "}", "SpannableString", "newLabel", "=", "new", "SpannableString", "(", "getLabel", "(", ")", ")", ";", "if", "(", "spans", "!=", "null", ")", "{", "for", "(", "Object", "span", ":", "spans", ")", "{", "newLabel", ".", "setSpan", "(", "span", ",", "0", ",", "newLabel", ".", "length", "(", ")", ",", "Spanned", ".", "SPAN_EXCLUSIVE_EXCLUSIVE", ")", ";", "}", "}", "setText", "(", "newLabel", ")", ";", "}" ]
Set the new label formatter and reformat the current label. This preserves current spans. @param formatter new label formatter
[ "Set", "the", "new", "label", "formatter", "and", "reformat", "the", "current", "label", ".", "This", "preserves", "current", "spans", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java#L77-L93
19,289
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java
DayView.setDayFormatterContentDescription
public void setDayFormatterContentDescription(DayFormatter formatter) { this.contentDescriptionFormatter = formatter == null ? this.formatter : formatter; setContentDescription(getContentDescriptionLabel()); }
java
public void setDayFormatterContentDescription(DayFormatter formatter) { this.contentDescriptionFormatter = formatter == null ? this.formatter : formatter; setContentDescription(getContentDescriptionLabel()); }
[ "public", "void", "setDayFormatterContentDescription", "(", "DayFormatter", "formatter", ")", "{", "this", ".", "contentDescriptionFormatter", "=", "formatter", "==", "null", "?", "this", ".", "formatter", ":", "formatter", ";", "setContentDescription", "(", "getContentDescriptionLabel", "(", ")", ")", ";", "}" ]
Set the new content description formatter and reformat the current content description. @param formatter new content description formatter
[ "Set", "the", "new", "content", "description", "formatter", "and", "reformat", "the", "current", "content", "description", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java#L100-L103
19,290
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java
CalendarPagerAdapter.setDateSelected
public void setDateSelected(CalendarDay day, boolean selected) { if (selected) { if (!selectedDates.contains(day)) { selectedDates.add(day); invalidateSelectedDates(); } } else { if (selectedDates.contains(day)) { selectedDates.remove(day); invalidateSelectedDates(); } } }
java
public void setDateSelected(CalendarDay day, boolean selected) { if (selected) { if (!selectedDates.contains(day)) { selectedDates.add(day); invalidateSelectedDates(); } } else { if (selectedDates.contains(day)) { selectedDates.remove(day); invalidateSelectedDates(); } } }
[ "public", "void", "setDateSelected", "(", "CalendarDay", "day", ",", "boolean", "selected", ")", "{", "if", "(", "selected", ")", "{", "if", "(", "!", "selectedDates", ".", "contains", "(", "day", ")", ")", "{", "selectedDates", ".", "add", "(", "day", ")", ";", "invalidateSelectedDates", "(", ")", ";", "}", "}", "else", "{", "if", "(", "selectedDates", ".", "contains", "(", "day", ")", ")", "{", "selectedDates", ".", "remove", "(", "day", ")", ";", "invalidateSelectedDates", "(", ")", ";", "}", "}", "}" ]
Select or un-select a day. @param day Day to select or un-select @param selected Whether to select or un-select the day from the list. @see CalendarPagerAdapter#selectRange(CalendarDay, CalendarDay)
[ "Select", "or", "un", "-", "select", "a", "day", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java#L303-L315
19,291
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java
CalendarPagerAdapter.selectRange
public void selectRange(final CalendarDay first, final CalendarDay last) { selectedDates.clear(); // Copy to start from the first day and increment LocalDate temp = LocalDate.of(first.getYear(), first.getMonth(), first.getDay()); // for comparison final LocalDate end = last.getDate(); while( temp.isBefore(end) || temp.equals(end) ) { selectedDates.add(CalendarDay.from(temp)); temp = temp.plusDays(1); } invalidateSelectedDates(); }
java
public void selectRange(final CalendarDay first, final CalendarDay last) { selectedDates.clear(); // Copy to start from the first day and increment LocalDate temp = LocalDate.of(first.getYear(), first.getMonth(), first.getDay()); // for comparison final LocalDate end = last.getDate(); while( temp.isBefore(end) || temp.equals(end) ) { selectedDates.add(CalendarDay.from(temp)); temp = temp.plusDays(1); } invalidateSelectedDates(); }
[ "public", "void", "selectRange", "(", "final", "CalendarDay", "first", ",", "final", "CalendarDay", "last", ")", "{", "selectedDates", ".", "clear", "(", ")", ";", "// Copy to start from the first day and increment", "LocalDate", "temp", "=", "LocalDate", ".", "of", "(", "first", ".", "getYear", "(", ")", ",", "first", ".", "getMonth", "(", ")", ",", "first", ".", "getDay", "(", ")", ")", ";", "// for comparison", "final", "LocalDate", "end", "=", "last", ".", "getDate", "(", ")", ";", "while", "(", "temp", ".", "isBefore", "(", "end", ")", "||", "temp", ".", "equals", "(", "end", ")", ")", "{", "selectedDates", ".", "add", "(", "CalendarDay", ".", "from", "(", "temp", ")", ")", ";", "temp", "=", "temp", ".", "plusDays", "(", "1", ")", ";", "}", "invalidateSelectedDates", "(", ")", ";", "}" ]
Clear the previous selection, select the range of days from first to last, and finally invalidate. First day should be before last day, otherwise the selection won't happen. @param first The first day of the range. @param last The last day in the range. @see CalendarPagerAdapter#setDateSelected(CalendarDay, boolean)
[ "Clear", "the", "previous", "selection", "select", "the", "range", "of", "days", "from", "first", "to", "last", "and", "finally", "invalidate", ".", "First", "day", "should", "be", "before", "last", "day", "otherwise", "the", "selection", "won", "t", "happen", "." ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java#L325-L340
19,292
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewFacade.java
DayViewFacade.applyTo
void applyTo(DayViewFacade other) { if (selectionDrawable != null) { other.setSelectionDrawable(selectionDrawable); } if (backgroundDrawable != null) { other.setBackgroundDrawable(backgroundDrawable); } other.spans.addAll(spans); other.isDecorated |= this.isDecorated; other.daysDisabled = daysDisabled; }
java
void applyTo(DayViewFacade other) { if (selectionDrawable != null) { other.setSelectionDrawable(selectionDrawable); } if (backgroundDrawable != null) { other.setBackgroundDrawable(backgroundDrawable); } other.spans.addAll(spans); other.isDecorated |= this.isDecorated; other.daysDisabled = daysDisabled; }
[ "void", "applyTo", "(", "DayViewFacade", "other", ")", "{", "if", "(", "selectionDrawable", "!=", "null", ")", "{", "other", ".", "setSelectionDrawable", "(", "selectionDrawable", ")", ";", "}", "if", "(", "backgroundDrawable", "!=", "null", ")", "{", "other", ".", "setBackgroundDrawable", "(", "backgroundDrawable", ")", ";", "}", "other", ".", "spans", ".", "addAll", "(", "spans", ")", ";", "other", ".", "isDecorated", "|=", "this", ".", "isDecorated", ";", "other", ".", "daysDisabled", "=", "daysDisabled", ";", "}" ]
Apply things set this to other @param other facade to apply our data to
[ "Apply", "things", "set", "this", "to", "other" ]
04fae8175fd034d0a7131f8cb253cae883a88aa2
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewFacade.java#L89-L99
19,293
javamelody/javamelody
javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/MonitoringEndpoint.java
MonitoringEndpoint.report
@ReadOperation public void report() throws ServletException, IOException { final ServletRequestAttributes currentRequestAttributes = (ServletRequestAttributes) RequestContextHolder .currentRequestAttributes(); final HttpServletRequest httpServletRequest = currentRequestAttributes.getRequest(); final HttpServletResponse httpResponse = currentRequestAttributes.getResponse(); reportServlet.service(httpServletRequest, httpResponse); }
java
@ReadOperation public void report() throws ServletException, IOException { final ServletRequestAttributes currentRequestAttributes = (ServletRequestAttributes) RequestContextHolder .currentRequestAttributes(); final HttpServletRequest httpServletRequest = currentRequestAttributes.getRequest(); final HttpServletResponse httpResponse = currentRequestAttributes.getResponse(); reportServlet.service(httpServletRequest, httpResponse); }
[ "@", "ReadOperation", "public", "void", "report", "(", ")", "throws", "ServletException", ",", "IOException", "{", "final", "ServletRequestAttributes", "currentRequestAttributes", "=", "(", "ServletRequestAttributes", ")", "RequestContextHolder", ".", "currentRequestAttributes", "(", ")", ";", "final", "HttpServletRequest", "httpServletRequest", "=", "currentRequestAttributes", ".", "getRequest", "(", ")", ";", "final", "HttpServletResponse", "httpResponse", "=", "currentRequestAttributes", ".", "getResponse", "(", ")", ";", "reportServlet", ".", "service", "(", "httpServletRequest", ",", "httpResponse", ")", ";", "}" ]
Display a report page. @throws ServletException e @throws IOException e
[ "Display", "a", "report", "page", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/MonitoringEndpoint.java#L63-L71
19,294
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java
PayloadNameRequestWrapper.parseGwtRpcMethodName
@SuppressWarnings("resource") private static String parseGwtRpcMethodName(InputStream stream, String charEncoding) { //commented out code uses GWT-user library for a more 'proper' approach. //GWT-user library approach is more future-proof, but requires more dependency management. // RPCRequest decodeRequest = RPC.decodeRequest(readLine); // gwtmethodname = decodeRequest.getMethod().getName(); try { final Scanner scanner; if (charEncoding == null) { scanner = new Scanner(stream); } else { scanner = new Scanner(stream, charEncoding); } scanner.useDelimiter(GWT_RPC_SEPARATOR_CHAR_PATTERN); //AbstractSerializationStream.RPC_SEPARATOR_CHAR //AbstractSerializationStreamReader.prepareToRead(...) scanner.next(); //stream version number scanner.next(); //flags //ServerSerializationStreamReader.deserializeStringTable() scanner.next(); //type name count //ServerSerializationStreamReader.preapreToRead(...) scanner.next(); //module base URL scanner.next(); //strong name //RPC.decodeRequest(...) scanner.next(); //service interface name return "." + scanner.next(); //service method name //note we don't close the scanner because we don't want to close the underlying stream } catch (final NoSuchElementException e) { LOG.debug("Unable to parse GWT-RPC request", e); //code above is best-effort - we were unable to parse GWT payload so //treat as a normal HTTP request return null; } }
java
@SuppressWarnings("resource") private static String parseGwtRpcMethodName(InputStream stream, String charEncoding) { //commented out code uses GWT-user library for a more 'proper' approach. //GWT-user library approach is more future-proof, but requires more dependency management. // RPCRequest decodeRequest = RPC.decodeRequest(readLine); // gwtmethodname = decodeRequest.getMethod().getName(); try { final Scanner scanner; if (charEncoding == null) { scanner = new Scanner(stream); } else { scanner = new Scanner(stream, charEncoding); } scanner.useDelimiter(GWT_RPC_SEPARATOR_CHAR_PATTERN); //AbstractSerializationStream.RPC_SEPARATOR_CHAR //AbstractSerializationStreamReader.prepareToRead(...) scanner.next(); //stream version number scanner.next(); //flags //ServerSerializationStreamReader.deserializeStringTable() scanner.next(); //type name count //ServerSerializationStreamReader.preapreToRead(...) scanner.next(); //module base URL scanner.next(); //strong name //RPC.decodeRequest(...) scanner.next(); //service interface name return "." + scanner.next(); //service method name //note we don't close the scanner because we don't want to close the underlying stream } catch (final NoSuchElementException e) { LOG.debug("Unable to parse GWT-RPC request", e); //code above is best-effort - we were unable to parse GWT payload so //treat as a normal HTTP request return null; } }
[ "@", "SuppressWarnings", "(", "\"resource\"", ")", "private", "static", "String", "parseGwtRpcMethodName", "(", "InputStream", "stream", ",", "String", "charEncoding", ")", "{", "//commented out code uses GWT-user library for a more 'proper' approach.\r", "//GWT-user library approach is more future-proof, but requires more dependency management.\r", "//\t\t\t\tRPCRequest decodeRequest = RPC.decodeRequest(readLine);\r", "//\t\t\t\tgwtmethodname = decodeRequest.getMethod().getName();\r", "try", "{", "final", "Scanner", "scanner", ";", "if", "(", "charEncoding", "==", "null", ")", "{", "scanner", "=", "new", "Scanner", "(", "stream", ")", ";", "}", "else", "{", "scanner", "=", "new", "Scanner", "(", "stream", ",", "charEncoding", ")", ";", "}", "scanner", ".", "useDelimiter", "(", "GWT_RPC_SEPARATOR_CHAR_PATTERN", ")", ";", "//AbstractSerializationStream.RPC_SEPARATOR_CHAR\r", "//AbstractSerializationStreamReader.prepareToRead(...)\r", "scanner", ".", "next", "(", ")", ";", "//stream version number\r", "scanner", ".", "next", "(", ")", ";", "//flags\r", "//ServerSerializationStreamReader.deserializeStringTable()\r", "scanner", ".", "next", "(", ")", ";", "//type name count\r", "//ServerSerializationStreamReader.preapreToRead(...)\r", "scanner", ".", "next", "(", ")", ";", "//module base URL\r", "scanner", ".", "next", "(", ")", ";", "//strong name\r", "//RPC.decodeRequest(...)\r", "scanner", ".", "next", "(", ")", ";", "//service interface name\r", "return", "\".\"", "+", "scanner", ".", "next", "(", ")", ";", "//service method name\r", "//note we don't close the scanner because we don't want to close the underlying stream\r", "}", "catch", "(", "final", "NoSuchElementException", "e", ")", "{", "LOG", ".", "debug", "(", "\"Unable to parse GWT-RPC request\"", ",", "e", ")", ";", "//code above is best-effort - we were unable to parse GWT payload so\r", "//treat as a normal HTTP request\r", "return", "null", ";", "}", "}" ]
Try to parse GWT-RPC method name from request body stream. Does not close the stream. @param stream GWT-RPC request body stream @nonnull @param charEncoding character encoding of stream, or null for platform default @null @return GWT-RPC method name, or null if unable to parse @null
[ "Try", "to", "parse", "GWT", "-", "RPC", "method", "name", "from", "request", "body", "stream", ".", "Does", "not", "close", "the", "stream", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java#L152-L191
19,295
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java
PayloadNameRequestWrapper.scanForChildTag
static boolean scanForChildTag(XMLStreamReader reader, String tagName) throws XMLStreamException { assert reader.isStartElement(); int level = -1; while (reader.hasNext()) { //keep track of level so we only search children, not descendants if (reader.isStartElement()) { level++; } else if (reader.isEndElement()) { level--; } if (level < 0) { //end parent tag - no more children break; } reader.next(); if (level == 0 && reader.isStartElement() && reader.getLocalName().equals(tagName)) { return true; //found } } return false; //got to end of parent element and not found }
java
static boolean scanForChildTag(XMLStreamReader reader, String tagName) throws XMLStreamException { assert reader.isStartElement(); int level = -1; while (reader.hasNext()) { //keep track of level so we only search children, not descendants if (reader.isStartElement()) { level++; } else if (reader.isEndElement()) { level--; } if (level < 0) { //end parent tag - no more children break; } reader.next(); if (level == 0 && reader.isStartElement() && reader.getLocalName().equals(tagName)) { return true; //found } } return false; //got to end of parent element and not found }
[ "static", "boolean", "scanForChildTag", "(", "XMLStreamReader", "reader", ",", "String", "tagName", ")", "throws", "XMLStreamException", "{", "assert", "reader", ".", "isStartElement", "(", ")", ";", "int", "level", "=", "-", "1", ";", "while", "(", "reader", ".", "hasNext", "(", ")", ")", "{", "//keep track of level so we only search children, not descendants\r", "if", "(", "reader", ".", "isStartElement", "(", ")", ")", "{", "level", "++", ";", "}", "else", "if", "(", "reader", ".", "isEndElement", "(", ")", ")", "{", "level", "--", ";", "}", "if", "(", "level", "<", "0", ")", "{", "//end parent tag - no more children\r", "break", ";", "}", "reader", ".", "next", "(", ")", ";", "if", "(", "level", "==", "0", "&&", "reader", ".", "isStartElement", "(", ")", "&&", "reader", ".", "getLocalName", "(", ")", ".", "equals", "(", "tagName", ")", ")", "{", "return", "true", ";", "//found\r", "}", "}", "return", "false", ";", "//got to end of parent element and not found\r", "}" ]
Scan xml for tag child of the current element @param reader reader, must be at "start element" @nonnull @param tagName name of child tag to find @nonnull @return if found tag @throws XMLStreamException on error
[ "Scan", "xml", "for", "tag", "child", "of", "the", "current", "element" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java#L201-L225
19,296
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java
PayloadNameRequestWrapper.parseSoapMethodName
private static String parseSoapMethodName(InputStream stream, String charEncoding) { try { // newInstance() et pas newFactory() pour java 1.5 (issue 367) final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // disable DTDs entirely for that factory factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); // disable external entities final XMLStreamReader xmlReader; if (charEncoding != null) { xmlReader = factory.createXMLStreamReader(stream, charEncoding); } else { xmlReader = factory.createXMLStreamReader(stream); } //best-effort parsing //start document, go to first tag xmlReader.nextTag(); //expect first tag to be "Envelope" if (!"Envelope".equals(xmlReader.getLocalName())) { LOG.debug("Unexpected first tag of SOAP request: '" + xmlReader.getLocalName() + "' (expected 'Envelope')"); return null; //failed } //scan for body tag if (!scanForChildTag(xmlReader, "Body")) { LOG.debug("Unable to find SOAP 'Body' tag"); return null; //failed } xmlReader.nextTag(); //tag is method name return "." + xmlReader.getLocalName(); } catch (final XMLStreamException e) { LOG.debug("Unable to parse SOAP request", e); //failed return null; } }
java
private static String parseSoapMethodName(InputStream stream, String charEncoding) { try { // newInstance() et pas newFactory() pour java 1.5 (issue 367) final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // disable DTDs entirely for that factory factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); // disable external entities final XMLStreamReader xmlReader; if (charEncoding != null) { xmlReader = factory.createXMLStreamReader(stream, charEncoding); } else { xmlReader = factory.createXMLStreamReader(stream); } //best-effort parsing //start document, go to first tag xmlReader.nextTag(); //expect first tag to be "Envelope" if (!"Envelope".equals(xmlReader.getLocalName())) { LOG.debug("Unexpected first tag of SOAP request: '" + xmlReader.getLocalName() + "' (expected 'Envelope')"); return null; //failed } //scan for body tag if (!scanForChildTag(xmlReader, "Body")) { LOG.debug("Unable to find SOAP 'Body' tag"); return null; //failed } xmlReader.nextTag(); //tag is method name return "." + xmlReader.getLocalName(); } catch (final XMLStreamException e) { LOG.debug("Unable to parse SOAP request", e); //failed return null; } }
[ "private", "static", "String", "parseSoapMethodName", "(", "InputStream", "stream", ",", "String", "charEncoding", ")", "{", "try", "{", "// newInstance() et pas newFactory() pour java 1.5 (issue 367)\r", "final", "XMLInputFactory", "factory", "=", "XMLInputFactory", ".", "newInstance", "(", ")", ";", "factory", ".", "setProperty", "(", "XMLInputFactory", ".", "SUPPORT_DTD", ",", "false", ")", ";", "// disable DTDs entirely for that factory\r", "factory", ".", "setProperty", "(", "XMLInputFactory", ".", "IS_SUPPORTING_EXTERNAL_ENTITIES", ",", "false", ")", ";", "// disable external entities\r", "final", "XMLStreamReader", "xmlReader", ";", "if", "(", "charEncoding", "!=", "null", ")", "{", "xmlReader", "=", "factory", ".", "createXMLStreamReader", "(", "stream", ",", "charEncoding", ")", ";", "}", "else", "{", "xmlReader", "=", "factory", ".", "createXMLStreamReader", "(", "stream", ")", ";", "}", "//best-effort parsing\r", "//start document, go to first tag\r", "xmlReader", ".", "nextTag", "(", ")", ";", "//expect first tag to be \"Envelope\"\r", "if", "(", "!", "\"Envelope\"", ".", "equals", "(", "xmlReader", ".", "getLocalName", "(", ")", ")", ")", "{", "LOG", ".", "debug", "(", "\"Unexpected first tag of SOAP request: '\"", "+", "xmlReader", ".", "getLocalName", "(", ")", "+", "\"' (expected 'Envelope')\"", ")", ";", "return", "null", ";", "//failed\r", "}", "//scan for body tag\r", "if", "(", "!", "scanForChildTag", "(", "xmlReader", ",", "\"Body\"", ")", ")", "{", "LOG", ".", "debug", "(", "\"Unable to find SOAP 'Body' tag\"", ")", ";", "return", "null", ";", "//failed\r", "}", "xmlReader", ".", "nextTag", "(", ")", ";", "//tag is method name\r", "return", "\".\"", "+", "xmlReader", ".", "getLocalName", "(", ")", ";", "}", "catch", "(", "final", "XMLStreamException", "e", ")", "{", "LOG", ".", "debug", "(", "\"Unable to parse SOAP request\"", ",", "e", ")", ";", "//failed\r", "return", "null", ";", "}", "}" ]
Try to parse SOAP method name from request body stream. Does not close the stream. @param stream SOAP request body stream @nonnull @param charEncoding character encoding of stream, or null for platform default @null @return SOAP method name, or null if unable to parse @null
[ "Try", "to", "parse", "SOAP", "method", "name", "from", "request", "body", "stream", ".", "Does", "not", "close", "the", "stream", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java#L234-L274
19,297
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MHtmlWriter.java
MHtmlWriter.writeHtml
protected void writeHtml(final MBasicTable table, final OutputStream outputStream, final boolean isSelection) throws IOException { final Writer out = new OutputStreamWriter(outputStream, "UTF-8"); final String eol = isSelection ? "\n" : System.getProperty("line.separator"); // eol = "\n" si sélection, "\r\n" sinon pour un fichier windows et "\n" pour un fichier unix out.write("<!-- Fichier genere par "); out.write(System.getProperty("user.name")); out.write(" le "); out.write(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG) .format(new Date())); out.write(" -->"); out.write(eol); out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.write("<html>"); out.write(eol); final String title = buildTitle(table); writeHtmlHead(title, out, eol); out.write("<body>"); out.write(eol); if (title != null) { out.write("<h3>"); out.write(title); out.write("</h3>"); } out.write(eol); writeHtmlTable(table, isSelection, out, eol); out.write("</body>"); out.write(eol); out.write("</html>"); out.flush(); }
java
protected void writeHtml(final MBasicTable table, final OutputStream outputStream, final boolean isSelection) throws IOException { final Writer out = new OutputStreamWriter(outputStream, "UTF-8"); final String eol = isSelection ? "\n" : System.getProperty("line.separator"); // eol = "\n" si sélection, "\r\n" sinon pour un fichier windows et "\n" pour un fichier unix out.write("<!-- Fichier genere par "); out.write(System.getProperty("user.name")); out.write(" le "); out.write(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG) .format(new Date())); out.write(" -->"); out.write(eol); out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.write("<html>"); out.write(eol); final String title = buildTitle(table); writeHtmlHead(title, out, eol); out.write("<body>"); out.write(eol); if (title != null) { out.write("<h3>"); out.write(title); out.write("</h3>"); } out.write(eol); writeHtmlTable(table, isSelection, out, eol); out.write("</body>"); out.write(eol); out.write("</html>"); out.flush(); }
[ "protected", "void", "writeHtml", "(", "final", "MBasicTable", "table", ",", "final", "OutputStream", "outputStream", ",", "final", "boolean", "isSelection", ")", "throws", "IOException", "{", "final", "Writer", "out", "=", "new", "OutputStreamWriter", "(", "outputStream", ",", "\"UTF-8\"", ")", ";", "final", "String", "eol", "=", "isSelection", "?", "\"\\n\"", ":", "System", ".", "getProperty", "(", "\"line.separator\"", ")", ";", "// eol = \"\\n\" si sélection, \"\\r\\n\" sinon pour un fichier windows et \"\\n\" pour un fichier unix\r", "out", ".", "write", "(", "\"<!-- Fichier genere par \"", ")", ";", "out", ".", "write", "(", "System", ".", "getProperty", "(", "\"user.name\"", ")", ")", ";", "out", ".", "write", "(", "\" le \"", ")", ";", "out", ".", "write", "(", "DateFormat", ".", "getDateTimeInstance", "(", "DateFormat", ".", "LONG", ",", "DateFormat", ".", "LONG", ")", ".", "format", "(", "new", "Date", "(", ")", ")", ")", ";", "out", ".", "write", "(", "\" -->\"", ")", ";", "out", ".", "write", "(", "eol", ")", ";", "out", ".", "write", "(", "\"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.01 Transitional//EN\\\">\"", ")", ";", "out", ".", "write", "(", "\"<html>\"", ")", ";", "out", ".", "write", "(", "eol", ")", ";", "final", "String", "title", "=", "buildTitle", "(", "table", ")", ";", "writeHtmlHead", "(", "title", ",", "out", ",", "eol", ")", ";", "out", ".", "write", "(", "\"<body>\"", ")", ";", "out", ".", "write", "(", "eol", ")", ";", "if", "(", "title", "!=", "null", ")", "{", "out", ".", "write", "(", "\"<h3>\"", ")", ";", "out", ".", "write", "(", "title", ")", ";", "out", ".", "write", "(", "\"</h3>\"", ")", ";", "}", "out", ".", "write", "(", "eol", ")", ";", "writeHtmlTable", "(", "table", ",", "isSelection", ",", "out", ",", "eol", ")", ";", "out", ".", "write", "(", "\"</body>\"", ")", ";", "out", ".", "write", "(", "eol", ")", ";", "out", ".", "write", "(", "\"</html>\"", ")", ";", "out", ".", "flush", "(", ")", ";", "}" ]
Exporte une JTable dans un fichier au format html. @param table MBasicTable @param outputStream OutputStream @param isSelection boolean @throws IOException Erreur disque
[ "Exporte", "une", "JTable", "dans", "un", "fichier", "au", "format", "html", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MHtmlWriter.java#L93-L127
19,298
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/JdbcWrapper.java
JdbcWrapper.createJavaxConnectionManagerProxy
private Object createJavaxConnectionManagerProxy(Object javaxConnectionManager) { assert javaxConnectionManager != null; final InvocationHandler invocationHandler = new ConnectionManagerInvocationHandler( javaxConnectionManager); return createProxy(javaxConnectionManager, invocationHandler); }
java
private Object createJavaxConnectionManagerProxy(Object javaxConnectionManager) { assert javaxConnectionManager != null; final InvocationHandler invocationHandler = new ConnectionManagerInvocationHandler( javaxConnectionManager); return createProxy(javaxConnectionManager, invocationHandler); }
[ "private", "Object", "createJavaxConnectionManagerProxy", "(", "Object", "javaxConnectionManager", ")", "{", "assert", "javaxConnectionManager", "!=", "null", ";", "final", "InvocationHandler", "invocationHandler", "=", "new", "ConnectionManagerInvocationHandler", "(", "javaxConnectionManager", ")", ";", "return", "createProxy", "(", "javaxConnectionManager", ",", "invocationHandler", ")", ";", "}" ]
pour jboss ou glassfish
[ "pour", "jboss", "ou", "glassfish" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/JdbcWrapper.java#L715-L720
19,299
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/MonitoringInterceptor.java
MonitoringInterceptor.getRequestName
protected String getRequestName(InvocationContext context) { final Method method = context.getMethod(); return method.getDeclaringClass().getSimpleName() + '.' + method.getName(); }
java
protected String getRequestName(InvocationContext context) { final Method method = context.getMethod(); return method.getDeclaringClass().getSimpleName() + '.' + method.getName(); }
[ "protected", "String", "getRequestName", "(", "InvocationContext", "context", ")", "{", "final", "Method", "method", "=", "context", ".", "getMethod", "(", ")", ";", "return", "method", ".", "getDeclaringClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "'", "'", "+", "method", ".", "getName", "(", ")", ";", "}" ]
Determine request name for an invocation context. @param context the invocation context (not null) @return the request name for this invocation
[ "Determine", "request", "name", "for", "an", "invocation", "context", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/MonitoringInterceptor.java#L96-L99