repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
alkacon/opencms-core
src/org/opencms/search/galleries/CmsGallerySearchParameters.java
CmsGallerySearchParameters.addFoldersToSearchIn
private void addFoldersToSearchIn(final List<String> folders) { if (null == folders) { return; } for (String folder : folders) { if (!CmsResource.isFolder(folder)) { folder += "/"; } m_foldersToSearchIn.add(folder); } }
java
private void addFoldersToSearchIn(final List<String> folders) { if (null == folders) { return; } for (String folder : folders) { if (!CmsResource.isFolder(folder)) { folder += "/"; } m_foldersToSearchIn.add(folder); } }
[ "private", "void", "addFoldersToSearchIn", "(", "final", "List", "<", "String", ">", "folders", ")", "{", "if", "(", "null", "==", "folders", ")", "{", "return", ";", "}", "for", "(", "String", "folder", ":", "folders", ")", "{", "if", "(", "!", "Cms...
Adds folders to perform the search in. @param folders Folders to search in.
[ "Adds", "folders", "to", "perform", "the", "search", "in", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/galleries/CmsGallerySearchParameters.java#L757-L770
train
alkacon/opencms-core
src/org/opencms/search/galleries/CmsGallerySearchParameters.java
CmsGallerySearchParameters.setSearchScopeFilter
private void setSearchScopeFilter(CmsObject cms) { final List<String> searchRoots = CmsSearchUtil.computeScopeFolders(cms, this); // If the resource types contain the type "function" also // add "/system/modules/" to the search path if ((null != getResourceTypes()) && containsFunctionType(getResourceTypes())) { searchRoots.add("/system/modules/"); } addFoldersToSearchIn(searchRoots); }
java
private void setSearchScopeFilter(CmsObject cms) { final List<String> searchRoots = CmsSearchUtil.computeScopeFolders(cms, this); // If the resource types contain the type "function" also // add "/system/modules/" to the search path if ((null != getResourceTypes()) && containsFunctionType(getResourceTypes())) { searchRoots.add("/system/modules/"); } addFoldersToSearchIn(searchRoots); }
[ "private", "void", "setSearchScopeFilter", "(", "CmsObject", "cms", ")", "{", "final", "List", "<", "String", ">", "searchRoots", "=", "CmsSearchUtil", ".", "computeScopeFolders", "(", "cms", ",", "this", ")", ";", "// If the resource types contain the type \"function...
Sets the search scope. @param cms The current CmsObject object.
[ "Sets", "the", "search", "scope", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/galleries/CmsGallerySearchParameters.java#L875-L887
train
alkacon/opencms-core
src-setup/org/opencms/setup/ui/CmsDbSettingsPanel.java
CmsDbSettingsPanel.dbProp
private String dbProp(String name) { String dbType = m_setupBean.getDatabase(); Object prop = m_setupBean.getDatabaseProperties().get(dbType).get(dbType + "." + name); if (prop == null) { return ""; } return prop.toString(); }
java
private String dbProp(String name) { String dbType = m_setupBean.getDatabase(); Object prop = m_setupBean.getDatabaseProperties().get(dbType).get(dbType + "." + name); if (prop == null) { return ""; } return prop.toString(); }
[ "private", "String", "dbProp", "(", "String", "name", ")", "{", "String", "dbType", "=", "m_setupBean", ".", "getDatabase", "(", ")", ";", "Object", "prop", "=", "m_setupBean", ".", "getDatabaseProperties", "(", ")", ".", "get", "(", "dbType", ")", ".", ...
Accesses a property from the DB configuration for the selected DB. @param name the name of the property @return the value of the property
[ "Accesses", "a", "property", "from", "the", "DB", "configuration", "for", "the", "selected", "DB", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/ui/CmsDbSettingsPanel.java#L326-L334
train
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/CmsPopup.java
CmsPopup.add
protected void add(Widget child, Element container) { // Detach new child. child.removeFromParent(); // Logical attach. getChildren().add(child); // Physical attach. DOM.appendChild(container, child.getElement()); // Adopt. adopt(child); }
java
protected void add(Widget child, Element container) { // Detach new child. child.removeFromParent(); // Logical attach. getChildren().add(child); // Physical attach. DOM.appendChild(container, child.getElement()); // Adopt. adopt(child); }
[ "protected", "void", "add", "(", "Widget", "child", ",", "Element", "container", ")", "{", "// Detach new child.", "child", ".", "removeFromParent", "(", ")", ";", "// Logical attach.", "getChildren", "(", ")", ".", "add", "(", "child", ")", ";", "// Physical ...
Adds a new child widget to the panel, attaching its Element to the specified container Element. @param child the child widget to be added @param container the element within which the child will be contained
[ "Adds", "a", "new", "child", "widget", "to", "the", "panel", "attaching", "its", "Element", "to", "the", "specified", "container", "Element", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsPopup.java#L1058-L1071
train
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/CmsPopup.java
CmsPopup.adjustIndex
protected int adjustIndex(Widget child, int beforeIndex) { checkIndexBoundsForInsertion(beforeIndex); // Check to see if this widget is already a direct child. if (child.getParent() == this) { // If the Widget's previous position was left of the desired new position // shift the desired position left to reflect the removal int idx = getWidgetIndex(child); if (idx < beforeIndex) { beforeIndex--; } } return beforeIndex; }
java
protected int adjustIndex(Widget child, int beforeIndex) { checkIndexBoundsForInsertion(beforeIndex); // Check to see if this widget is already a direct child. if (child.getParent() == this) { // If the Widget's previous position was left of the desired new position // shift the desired position left to reflect the removal int idx = getWidgetIndex(child); if (idx < beforeIndex) { beforeIndex--; } } return beforeIndex; }
[ "protected", "int", "adjustIndex", "(", "Widget", "child", ",", "int", "beforeIndex", ")", "{", "checkIndexBoundsForInsertion", "(", "beforeIndex", ")", ";", "// Check to see if this widget is already a direct child.", "if", "(", "child", ".", "getParent", "(", ")", "...
Adjusts beforeIndex to account for the possibility that the given widget is already a child of this panel. @param child the widget that might be an existing child @param beforeIndex the index at which it will be added to this panel @return the modified index
[ "Adjusts", "beforeIndex", "to", "account", "for", "the", "possibility", "that", "the", "given", "widget", "is", "already", "a", "child", "of", "this", "panel", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsPopup.java#L1081-L1096
train
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/CmsPopup.java
CmsPopup.beginDragging
protected void beginDragging(MouseDownEvent event) { m_dragging = true; m_windowWidth = Window.getClientWidth(); m_clientLeft = Document.get().getBodyOffsetLeft(); m_clientTop = Document.get().getBodyOffsetTop(); DOM.setCapture(getElement()); m_dragStartX = event.getX(); m_dragStartY = event.getY(); addStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().dragging()); }
java
protected void beginDragging(MouseDownEvent event) { m_dragging = true; m_windowWidth = Window.getClientWidth(); m_clientLeft = Document.get().getBodyOffsetLeft(); m_clientTop = Document.get().getBodyOffsetTop(); DOM.setCapture(getElement()); m_dragStartX = event.getX(); m_dragStartY = event.getY(); addStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().dragging()); }
[ "protected", "void", "beginDragging", "(", "MouseDownEvent", "event", ")", "{", "m_dragging", "=", "true", ";", "m_windowWidth", "=", "Window", ".", "getClientWidth", "(", ")", ";", "m_clientLeft", "=", "Document", ".", "get", "(", ")", ".", "getBodyOffsetLeft...
Called on mouse down in the caption area, begins the dragging loop by turning on event capture. @see DOM#setCapture @see #continueDragging @param event the mouse down event that triggered dragging
[ "Called", "on", "mouse", "down", "in", "the", "caption", "area", "begins", "the", "dragging", "loop", "by", "turning", "on", "event", "capture", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsPopup.java#L1106-L1116
train
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/CmsPopup.java
CmsPopup.endDragging
protected void endDragging(MouseUpEvent event) { m_dragging = false; DOM.releaseCapture(getElement()); removeStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().dragging()); }
java
protected void endDragging(MouseUpEvent event) { m_dragging = false; DOM.releaseCapture(getElement()); removeStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().dragging()); }
[ "protected", "void", "endDragging", "(", "MouseUpEvent", "event", ")", "{", "m_dragging", "=", "false", ";", "DOM", ".", "releaseCapture", "(", "getElement", "(", ")", ")", ";", "removeStyleName", "(", "I_CmsLayoutBundle", ".", "INSTANCE", ".", "dialogCss", "(...
Called on mouse up in the caption area, ends dragging by ending event capture. @param event the mouse up event that ended dragging @see DOM#releaseCapture @see #beginDragging @see #endDragging
[ "Called", "on", "mouse", "up", "in", "the", "caption", "area", "ends", "dragging", "by", "ending", "event", "capture", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsPopup.java#L1228-L1233
train
alkacon/opencms-core
src/org/opencms/ui/actions/CmsCategoriesDialogAction.java
CmsCategoriesDialogAction.getParams
public Map<String, String> getParams() { Map<String, String> params = new HashMap<>(1); params.put(PARAM_COLLAPSED, Boolean.TRUE.toString()); return params; }
java
public Map<String, String> getParams() { Map<String, String> params = new HashMap<>(1); params.put(PARAM_COLLAPSED, Boolean.TRUE.toString()); return params; }
[ "public", "Map", "<", "String", ",", "String", ">", "getParams", "(", ")", "{", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "HashMap", "<>", "(", "1", ")", ";", "params", ".", "put", "(", "PARAM_COLLAPSED", ",", "Boolean", ".", ...
Add the option specifying if the categories should be displayed collapsed when the dialog opens. @see org.opencms.ui.actions.I_CmsADEAction#getParams()
[ "Add", "the", "option", "specifying", "if", "the", "categories", "should", "be", "displayed", "collapsed", "when", "the", "dialog", "opens", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/actions/CmsCategoriesDialogAction.java#L117-L122
train
alkacon/opencms-core
src/org/opencms/search/solr/spellchecking/CmsSpellcheckDictionaryIndexer.java
CmsSpellcheckDictionaryIndexer.updatingIndexNecessesary
public static boolean updatingIndexNecessesary(CmsObject cms) { // Set request to the offline project. setCmsOfflineProject(cms); // Check whether the spellcheck index directories are empty. // If they are, the index has to be built obviously. if (isSolrSpellcheckIndexDirectoryEmpty()) { return true; } // Compare the most recent date of a dictionary with the oldest timestamp // that determines when an index has been built. long dateMostRecentDictionary = getMostRecentDate(cms); long dateOldestIndexWrite = getOldestIndexDate(cms); return dateMostRecentDictionary > dateOldestIndexWrite; }
java
public static boolean updatingIndexNecessesary(CmsObject cms) { // Set request to the offline project. setCmsOfflineProject(cms); // Check whether the spellcheck index directories are empty. // If they are, the index has to be built obviously. if (isSolrSpellcheckIndexDirectoryEmpty()) { return true; } // Compare the most recent date of a dictionary with the oldest timestamp // that determines when an index has been built. long dateMostRecentDictionary = getMostRecentDate(cms); long dateOldestIndexWrite = getOldestIndexDate(cms); return dateMostRecentDictionary > dateOldestIndexWrite; }
[ "public", "static", "boolean", "updatingIndexNecessesary", "(", "CmsObject", "cms", ")", "{", "// Set request to the offline project.", "setCmsOfflineProject", "(", "cms", ")", ";", "// Check whether the spellcheck index directories are empty.", "// If they are, the index has to be b...
Checks whether a built of the indices is necessary. @param cms The appropriate CmsObject instance. @return true, if the spellcheck indices have to be rebuilt, otherwise false
[ "Checks", "whether", "a", "built", "of", "the", "indices", "is", "necessary", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/solr/spellchecking/CmsSpellcheckDictionaryIndexer.java#L236-L253
train
alkacon/opencms-core
src/org/opencms/search/solr/spellchecking/CmsSpellcheckDictionaryIndexer.java
CmsSpellcheckDictionaryIndexer.getSolrSpellcheckRfsPath
private static String getSolrSpellcheckRfsPath() { String sPath = OpenCms.getSystemInfo().getWebInfRfsPath(); if (!OpenCms.getSystemInfo().getWebInfRfsPath().endsWith(File.separator)) { sPath += File.separator; } return sPath + "solr" + File.separator + "spellcheck" + File.separator + "data"; }
java
private static String getSolrSpellcheckRfsPath() { String sPath = OpenCms.getSystemInfo().getWebInfRfsPath(); if (!OpenCms.getSystemInfo().getWebInfRfsPath().endsWith(File.separator)) { sPath += File.separator; } return sPath + "solr" + File.separator + "spellcheck" + File.separator + "data"; }
[ "private", "static", "String", "getSolrSpellcheckRfsPath", "(", ")", "{", "String", "sPath", "=", "OpenCms", ".", "getSystemInfo", "(", ")", ".", "getWebInfRfsPath", "(", ")", ";", "if", "(", "!", "OpenCms", ".", "getSystemInfo", "(", ")", ".", "getWebInfRfs...
Returns the path in the RFS where the Solr spellcheck files reside. @return String representation of Solrs spellcheck RFS path.
[ "Returns", "the", "path", "in", "the", "RFS", "where", "the", "Solr", "spellcheck", "files", "reside", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/solr/spellchecking/CmsSpellcheckDictionaryIndexer.java#L395-L404
train
alkacon/opencms-core
src/org/opencms/search/solr/spellchecking/CmsSpellcheckDictionaryIndexer.java
CmsSpellcheckDictionaryIndexer.readAndAddDocumentsFromStream
private static void readAndAddDocumentsFromStream( final SolrClient client, final String lang, final InputStream is, final List<SolrInputDocument> documents, final boolean closeStream) { final BufferedReader br = new BufferedReader(new InputStreamReader(is)); try { String line = br.readLine(); while (null != line) { final SolrInputDocument document = new SolrInputDocument(); // Each field is named after the schema "entry_xx" where xx denotes // the two digit language code. See the file spellcheck/conf/schema.xml. document.addField("entry_" + lang, line); documents.add(document); // Prevent OutOfMemoryExceptions ... if (documents.size() >= MAX_LIST_SIZE) { addDocuments(client, documents, false); documents.clear(); } line = br.readLine(); } } catch (IOException e) { LOG.error("Could not read spellcheck dictionary from input stream."); } catch (SolrServerException e) { LOG.error("Error while adding documents to Solr server. "); } finally { try { if (closeStream) { br.close(); } } catch (Exception e) { // Nothing to do here anymore .... } } }
java
private static void readAndAddDocumentsFromStream( final SolrClient client, final String lang, final InputStream is, final List<SolrInputDocument> documents, final boolean closeStream) { final BufferedReader br = new BufferedReader(new InputStreamReader(is)); try { String line = br.readLine(); while (null != line) { final SolrInputDocument document = new SolrInputDocument(); // Each field is named after the schema "entry_xx" where xx denotes // the two digit language code. See the file spellcheck/conf/schema.xml. document.addField("entry_" + lang, line); documents.add(document); // Prevent OutOfMemoryExceptions ... if (documents.size() >= MAX_LIST_SIZE) { addDocuments(client, documents, false); documents.clear(); } line = br.readLine(); } } catch (IOException e) { LOG.error("Could not read spellcheck dictionary from input stream."); } catch (SolrServerException e) { LOG.error("Error while adding documents to Solr server. "); } finally { try { if (closeStream) { br.close(); } } catch (Exception e) { // Nothing to do here anymore .... } } }
[ "private", "static", "void", "readAndAddDocumentsFromStream", "(", "final", "SolrClient", "client", ",", "final", "String", "lang", ",", "final", "InputStream", "is", ",", "final", "List", "<", "SolrInputDocument", ">", "documents", ",", "final", "boolean", "close...
Parses the dictionary from an InputStream. @param client The SolrClient instance object. @param lang The language of the dictionary. @param is The InputStream object. @param documents List to put the assembled SolrInputObjects into. @param closeStream boolean flag that determines whether to close the inputstream or not.
[ "Parses", "the", "dictionary", "from", "an", "InputStream", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/solr/spellchecking/CmsSpellcheckDictionaryIndexer.java#L439-L479
train
alkacon/opencms-core
src/org/opencms/search/solr/spellchecking/CmsSpellcheckDictionaryIndexer.java
CmsSpellcheckDictionaryIndexer.setCmsOfflineProject
private static void setCmsOfflineProject(CmsObject cms) { if (null == cms) { return; } final CmsRequestContext cmsContext = cms.getRequestContext(); final CmsProject cmsProject = cmsContext.getCurrentProject(); if (cmsProject.isOnlineProject()) { CmsProject cmsOfflineProject; try { cmsOfflineProject = cms.readProject("Offline"); cmsContext.setCurrentProject(cmsOfflineProject); } catch (CmsException e) { LOG.warn("Could not set the current project to \"Offline\". "); } } }
java
private static void setCmsOfflineProject(CmsObject cms) { if (null == cms) { return; } final CmsRequestContext cmsContext = cms.getRequestContext(); final CmsProject cmsProject = cmsContext.getCurrentProject(); if (cmsProject.isOnlineProject()) { CmsProject cmsOfflineProject; try { cmsOfflineProject = cms.readProject("Offline"); cmsContext.setCurrentProject(cmsOfflineProject); } catch (CmsException e) { LOG.warn("Could not set the current project to \"Offline\". "); } } }
[ "private", "static", "void", "setCmsOfflineProject", "(", "CmsObject", "cms", ")", "{", "if", "(", "null", "==", "cms", ")", "{", "return", ";", "}", "final", "CmsRequestContext", "cmsContext", "=", "cms", ".", "getRequestContext", "(", ")", ";", "final", ...
Sets the appropriate OpenCms context. @param cms The OpenCms instance object.
[ "Sets", "the", "appropriate", "OpenCms", "context", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/solr/spellchecking/CmsSpellcheckDictionaryIndexer.java#L485-L503
train
alkacon/opencms-core
src/org/opencms/ui/CmsUserIconHelper.java
CmsUserIconHelper.toPath
private String toPath(String name, IconSize size) { return CmsStringUtil.joinPaths(CmsWorkplace.getSkinUri(), ICON_FOLDER, "" + name.hashCode()) + size.getSuffix(); }
java
private String toPath(String name, IconSize size) { return CmsStringUtil.joinPaths(CmsWorkplace.getSkinUri(), ICON_FOLDER, "" + name.hashCode()) + size.getSuffix(); }
[ "private", "String", "toPath", "(", "String", "name", ",", "IconSize", "size", ")", "{", "return", "CmsStringUtil", ".", "joinPaths", "(", "CmsWorkplace", ".", "getSkinUri", "(", ")", ",", "ICON_FOLDER", ",", "\"\"", "+", "name", ".", "hashCode", "(", ")",...
Transforms user name and icon size into the image path. @param name the user name @param size IconSize to get icon for @return the path
[ "Transforms", "user", "name", "and", "icon", "size", "into", "the", "image", "path", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/CmsUserIconHelper.java#L444-L447
train
alkacon/opencms-core
src/org/opencms/ui/CmsUserIconHelper.java
CmsUserIconHelper.toRfsName
private String toRfsName(String name, IconSize size) { return CmsStringUtil.joinPaths(m_cache.getRepositoryPath(), "" + name.hashCode()) + size.getSuffix(); }
java
private String toRfsName(String name, IconSize size) { return CmsStringUtil.joinPaths(m_cache.getRepositoryPath(), "" + name.hashCode()) + size.getSuffix(); }
[ "private", "String", "toRfsName", "(", "String", "name", ",", "IconSize", "size", ")", "{", "return", "CmsStringUtil", ".", "joinPaths", "(", "m_cache", ".", "getRepositoryPath", "(", ")", ",", "\"\"", "+", "name", ".", "hashCode", "(", ")", ")", "+", "s...
Transforms user name and icon size into the rfs image path. @param name the user name @param size IconSize to get icon for @return the path
[ "Transforms", "user", "name", "and", "icon", "size", "into", "the", "rfs", "image", "path", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/CmsUserIconHelper.java#L457-L460
train
alkacon/opencms-core
src-modules/org/opencms/workplace/search/CmsSearchDialog.java
CmsSearchDialog.getIndex
private I_CmsSearchIndex getIndex() { I_CmsSearchIndex index = null; // get the configured index or the selected index if (isInitialCall()) { // the search form is in the initial state // get the configured index index = OpenCms.getSearchManager().getIndex(getSettings().getUserSettings().getWorkplaceSearchIndexName()); } else { // the search form is not in the inital state, the submit button was used already or the // search index was changed already // get the selected index in the search dialog index = OpenCms.getSearchManager().getIndex(getJsp().getRequest().getParameter("indexName.0")); } return index; }
java
private I_CmsSearchIndex getIndex() { I_CmsSearchIndex index = null; // get the configured index or the selected index if (isInitialCall()) { // the search form is in the initial state // get the configured index index = OpenCms.getSearchManager().getIndex(getSettings().getUserSettings().getWorkplaceSearchIndexName()); } else { // the search form is not in the inital state, the submit button was used already or the // search index was changed already // get the selected index in the search dialog index = OpenCms.getSearchManager().getIndex(getJsp().getRequest().getParameter("indexName.0")); } return index; }
[ "private", "I_CmsSearchIndex", "getIndex", "(", ")", "{", "I_CmsSearchIndex", "index", "=", "null", ";", "// get the configured index or the selected index", "if", "(", "isInitialCall", "(", ")", ")", "{", "// the search form is in the initial state", "// get the configured i...
Gets the index to use in the search. @return the index to use in the search
[ "Gets", "the", "index", "to", "use", "in", "the", "search", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/search/CmsSearchDialog.java#L313-L328
train
alkacon/opencms-core
src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java
CmsXmlConfigUpdater.transform
public void transform(String name, String transform) throws Exception { File configFile = new File(m_configDir, name); File transformFile = new File(m_xsltDir, transform); try (InputStream stream = new FileInputStream(transformFile)) { StreamSource source = new StreamSource(stream); transform(configFile, source); } }
java
public void transform(String name, String transform) throws Exception { File configFile = new File(m_configDir, name); File transformFile = new File(m_xsltDir, transform); try (InputStream stream = new FileInputStream(transformFile)) { StreamSource source = new StreamSource(stream); transform(configFile, source); } }
[ "public", "void", "transform", "(", "String", "name", ",", "String", "transform", ")", "throws", "Exception", "{", "File", "configFile", "=", "new", "File", "(", "m_configDir", ",", "name", ")", ";", "File", "transformFile", "=", "new", "File", "(", "m_xsl...
Transforms a config file with an XSLT transform. @param name file name of the config file @param transform file name of the XSLT file @throws Exception if something goes wrong
[ "Transforms", "a", "config", "file", "with", "an", "XSLT", "transform", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java#L214-L222
train
alkacon/opencms-core
src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java
CmsXmlConfigUpdater.transformConfig
public void transformConfig() throws Exception { List<TransformEntry> entries = readTransformEntries(new File(m_xsltDir, "transforms.xml")); for (TransformEntry entry : entries) { transform(entry.getConfigFile(), entry.getXslt()); } m_isDone = true; }
java
public void transformConfig() throws Exception { List<TransformEntry> entries = readTransformEntries(new File(m_xsltDir, "transforms.xml")); for (TransformEntry entry : entries) { transform(entry.getConfigFile(), entry.getXslt()); } m_isDone = true; }
[ "public", "void", "transformConfig", "(", ")", "throws", "Exception", "{", "List", "<", "TransformEntry", ">", "entries", "=", "readTransformEntries", "(", "new", "File", "(", "m_xsltDir", ",", "\"transforms.xml\"", ")", ")", ";", "for", "(", "TransformEntry", ...
Transforms the configuration. @throws Exception if something goes wrong
[ "Transforms", "the", "configuration", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java#L229-L236
train
alkacon/opencms-core
src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java
CmsXmlConfigUpdater.validationErrors
public String validationErrors() { List<String> errors = new ArrayList<>(); for (File config : getConfigFiles()) { String filename = config.getName(); try (FileInputStream stream = new FileInputStream(config)) { CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(stream, false), new CmsXmlEntityResolver(null), true); } catch (CmsXmlException e) { errors.add(filename + ":" + e.getCause().getMessage()); } catch (Exception e) { errors.add(filename + ":" + e.getMessage()); } } if (errors.size() == 0) { return null; } String errString = CmsStringUtil.listAsString(errors, "\n"); JSONObject obj = new JSONObject(); try { obj.put("err", errString); } catch (JSONException e) { } return obj.toString(); }
java
public String validationErrors() { List<String> errors = new ArrayList<>(); for (File config : getConfigFiles()) { String filename = config.getName(); try (FileInputStream stream = new FileInputStream(config)) { CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(stream, false), new CmsXmlEntityResolver(null), true); } catch (CmsXmlException e) { errors.add(filename + ":" + e.getCause().getMessage()); } catch (Exception e) { errors.add(filename + ":" + e.getMessage()); } } if (errors.size() == 0) { return null; } String errString = CmsStringUtil.listAsString(errors, "\n"); JSONObject obj = new JSONObject(); try { obj.put("err", errString); } catch (JSONException e) { } return obj.toString(); }
[ "public", "String", "validationErrors", "(", ")", "{", "List", "<", "String", ">", "errors", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "File", "config", ":", "getConfigFiles", "(", ")", ")", "{", "String", "filename", "=", "config", "."...
Gets validation errors either as a JSON string, or null if there are no validation errors. @return the validation error JSON
[ "Gets", "validation", "errors", "either", "as", "a", "JSON", "string", "or", "null", "if", "there", "are", "no", "validation", "errors", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java#L243-L267
train
alkacon/opencms-core
src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java
CmsXmlConfigUpdater.getConfigFiles
private List<File> getConfigFiles() { String[] filenames = { "opencms-modules.xml", "opencms-system.xml", "opencms-vfs.xml", "opencms-importexport.xml", "opencms-sites.xml", "opencms-variables.xml", "opencms-scheduler.xml", "opencms-workplace.xml", "opencms-search.xml"}; List<File> result = new ArrayList<>(); for (String fn : filenames) { File file = new File(m_configDir, fn); if (file.exists()) { result.add(file); } } return result; }
java
private List<File> getConfigFiles() { String[] filenames = { "opencms-modules.xml", "opencms-system.xml", "opencms-vfs.xml", "opencms-importexport.xml", "opencms-sites.xml", "opencms-variables.xml", "opencms-scheduler.xml", "opencms-workplace.xml", "opencms-search.xml"}; List<File> result = new ArrayList<>(); for (String fn : filenames) { File file = new File(m_configDir, fn); if (file.exists()) { result.add(file); } } return result; }
[ "private", "List", "<", "File", ">", "getConfigFiles", "(", ")", "{", "String", "[", "]", "filenames", "=", "{", "\"opencms-modules.xml\"", ",", "\"opencms-system.xml\"", ",", "\"opencms-vfs.xml\"", ",", "\"opencms-importexport.xml\"", ",", "\"opencms-sites.xml\"", ",...
Gets existing config files. @return the existing config files
[ "Gets", "existing", "config", "files", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java#L274-L294
train
alkacon/opencms-core
src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java
CmsXmlConfigUpdater.readTransformEntries
private List<TransformEntry> readTransformEntries(File file) throws Exception { List<TransformEntry> result = new ArrayList<>(); try (FileInputStream fis = new FileInputStream(file)) { byte[] data = CmsFileUtil.readFully(fis, false); Document doc = CmsXmlUtils.unmarshalHelper(data, null, false); for (Node node : doc.selectNodes("//transform")) { Element elem = ((Element)node); String xslt = elem.attributeValue("xslt"); String conf = elem.attributeValue("config"); TransformEntry entry = new TransformEntry(conf, xslt); result.add(entry); } } return result; }
java
private List<TransformEntry> readTransformEntries(File file) throws Exception { List<TransformEntry> result = new ArrayList<>(); try (FileInputStream fis = new FileInputStream(file)) { byte[] data = CmsFileUtil.readFully(fis, false); Document doc = CmsXmlUtils.unmarshalHelper(data, null, false); for (Node node : doc.selectNodes("//transform")) { Element elem = ((Element)node); String xslt = elem.attributeValue("xslt"); String conf = elem.attributeValue("config"); TransformEntry entry = new TransformEntry(conf, xslt); result.add(entry); } } return result; }
[ "private", "List", "<", "TransformEntry", ">", "readTransformEntries", "(", "File", "file", ")", "throws", "Exception", "{", "List", "<", "TransformEntry", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "(", "FileInputStream", "fis", "="...
Reads entries from transforms.xml. @param file the XML file @return the transform entries read from the file @throws Exception if something goes wrong
[ "Reads", "entries", "from", "transforms", ".", "xml", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java#L304-L319
train
alkacon/opencms-core
src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java
CmsXmlConfigUpdater.transform
private void transform(File file, Source transformSource) throws TransformerConfigurationException, IOException, SAXException, TransformerException, ParserConfigurationException { Transformer transformer = m_transformerFactory.newTransformer(transformSource); transformer.setOutputProperty(OutputKeys.ENCODING, "us-ascii"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); String configDirPath = m_configDir.getAbsolutePath(); configDirPath = configDirPath.replaceFirst("[/\\\\]$", ""); transformer.setParameter("configDir", configDirPath); XMLReader reader = m_parserFactory.newSAXParser().getXMLReader(); reader.setEntityResolver(NO_ENTITY_RESOLVER); Source source; if (file.exists()) { source = new SAXSource(reader, new InputSource(file.getCanonicalPath())); } else { source = new SAXSource(reader, new InputSource(new ByteArrayInputStream(DEFAULT_XML.getBytes("UTF-8")))); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); Result target = new StreamResult(baos); transformer.transform(source, target); byte[] transformedConfig = baos.toByteArray(); try (FileOutputStream output = new FileOutputStream(file)) { output.write(transformedConfig); } }
java
private void transform(File file, Source transformSource) throws TransformerConfigurationException, IOException, SAXException, TransformerException, ParserConfigurationException { Transformer transformer = m_transformerFactory.newTransformer(transformSource); transformer.setOutputProperty(OutputKeys.ENCODING, "us-ascii"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); String configDirPath = m_configDir.getAbsolutePath(); configDirPath = configDirPath.replaceFirst("[/\\\\]$", ""); transformer.setParameter("configDir", configDirPath); XMLReader reader = m_parserFactory.newSAXParser().getXMLReader(); reader.setEntityResolver(NO_ENTITY_RESOLVER); Source source; if (file.exists()) { source = new SAXSource(reader, new InputSource(file.getCanonicalPath())); } else { source = new SAXSource(reader, new InputSource(new ByteArrayInputStream(DEFAULT_XML.getBytes("UTF-8")))); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); Result target = new StreamResult(baos); transformer.transform(source, target); byte[] transformedConfig = baos.toByteArray(); try (FileOutputStream output = new FileOutputStream(file)) { output.write(transformedConfig); } }
[ "private", "void", "transform", "(", "File", "file", ",", "Source", "transformSource", ")", "throws", "TransformerConfigurationException", ",", "IOException", ",", "SAXException", ",", "TransformerException", ",", "ParserConfigurationException", "{", "Transformer", "trans...
Transforms a single configuration file using the given transformation source. @param file the configuration file @param transformSource the transform soruce @throws TransformerConfigurationException - @throws IOException - @throws SAXException - @throws TransformerException - @throws ParserConfigurationException -
[ "Transforms", "a", "single", "configuration", "file", "using", "the", "given", "transformation", "source", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java#L333-L362
train
alkacon/opencms-core
src/org/opencms/jsp/CmsJspNavElement.java
CmsJspNavElement.getSubNavigation
public List<CmsJspNavElement> getSubNavigation() { if (m_subNavigation == null) { if (m_resource.isFile()) { m_subNavigation = Collections.emptyList(); } else if (m_navContext == null) { try { throw new Exception("Can not get subnavigation because navigation context is not set."); } catch (Exception e) { LOG.warn(e.getLocalizedMessage(), e); m_subNavigation = Collections.emptyList(); } } else { CmsJspNavBuilder navBuilder = m_navContext.getNavBuilder(); m_subNavigation = navBuilder.getNavigationForFolder( navBuilder.getCmsObject().getSitePath(m_resource), m_navContext.getVisibility(), m_navContext.getFilter()); } } return m_subNavigation; }
java
public List<CmsJspNavElement> getSubNavigation() { if (m_subNavigation == null) { if (m_resource.isFile()) { m_subNavigation = Collections.emptyList(); } else if (m_navContext == null) { try { throw new Exception("Can not get subnavigation because navigation context is not set."); } catch (Exception e) { LOG.warn(e.getLocalizedMessage(), e); m_subNavigation = Collections.emptyList(); } } else { CmsJspNavBuilder navBuilder = m_navContext.getNavBuilder(); m_subNavigation = navBuilder.getNavigationForFolder( navBuilder.getCmsObject().getSitePath(m_resource), m_navContext.getVisibility(), m_navContext.getFilter()); } } return m_subNavigation; }
[ "public", "List", "<", "CmsJspNavElement", ">", "getSubNavigation", "(", ")", "{", "if", "(", "m_subNavigation", "==", "null", ")", "{", "if", "(", "m_resource", ".", "isFile", "(", ")", ")", "{", "m_subNavigation", "=", "Collections", ".", "emptyList", "(...
Gets the sub-entries of the navigation entry. @return the sub-entries
[ "Gets", "the", "sub", "-", "entries", "of", "the", "navigation", "entry", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspNavElement.java#L442-L465
train
alkacon/opencms-core
src/org/opencms/jsp/CmsJspNavElement.java
CmsJspNavElement.getLocaleProperties
private Map<String, String> getLocaleProperties() { if (m_localeProperties == null) { m_localeProperties = CmsCollectionsGenericWrapper.createLazyMap( new CmsProperty.CmsPropertyLocaleTransformer(m_properties, m_locale)); } return m_localeProperties; }
java
private Map<String, String> getLocaleProperties() { if (m_localeProperties == null) { m_localeProperties = CmsCollectionsGenericWrapper.createLazyMap( new CmsProperty.CmsPropertyLocaleTransformer(m_properties, m_locale)); } return m_localeProperties; }
[ "private", "Map", "<", "String", ",", "String", ">", "getLocaleProperties", "(", ")", "{", "if", "(", "m_localeProperties", "==", "null", ")", "{", "m_localeProperties", "=", "CmsCollectionsGenericWrapper", ".", "createLazyMap", "(", "new", "CmsProperty", ".", "...
Helper to get locale specific properties. @return the locale specific properties map.
[ "Helper", "to", "get", "locale", "specific", "properties", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspNavElement.java#L729-L736
train
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsPatternPanelDailyController.java
CmsPatternPanelDailyController.setEveryWorkingDay
public void setEveryWorkingDay(final boolean isEveryWorkingDay) { if (m_model.isEveryWorkingDay() != isEveryWorkingDay) { removeExceptionsOnChange(new Command() { public void execute() { m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay)); m_model.setInterval(getPatternDefaultValues().getInterval()); onValueChange(); } }); } }
java
public void setEveryWorkingDay(final boolean isEveryWorkingDay) { if (m_model.isEveryWorkingDay() != isEveryWorkingDay) { removeExceptionsOnChange(new Command() { public void execute() { m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay)); m_model.setInterval(getPatternDefaultValues().getInterval()); onValueChange(); } }); } }
[ "public", "void", "setEveryWorkingDay", "(", "final", "boolean", "isEveryWorkingDay", ")", "{", "if", "(", "m_model", ".", "isEveryWorkingDay", "(", ")", "!=", "isEveryWorkingDay", ")", "{", "removeExceptionsOnChange", "(", "new", "Command", "(", ")", "{", "publ...
Set the "everyWorkingDay" flag. @param isEveryWorkingDay flag, indicating if the event should take place every working day.
[ "Set", "the", "everyWorkingDay", "flag", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsPatternPanelDailyController.java#L61-L74
train
alkacon/opencms-core
src/org/opencms/ade/upload/CmsUploadBean.java
CmsUploadBean.removeListener
private void removeListener(CmsUUID listenerId) { getRequest().getSession().removeAttribute(SESSION_ATTRIBUTE_LISTENER_ID); m_listeners.remove(listenerId); }
java
private void removeListener(CmsUUID listenerId) { getRequest().getSession().removeAttribute(SESSION_ATTRIBUTE_LISTENER_ID); m_listeners.remove(listenerId); }
[ "private", "void", "removeListener", "(", "CmsUUID", "listenerId", ")", "{", "getRequest", "(", ")", ".", "getSession", "(", ")", ".", "removeAttribute", "(", "SESSION_ATTRIBUTE_LISTENER_ID", ")", ";", "m_listeners", ".", "remove", "(", "listenerId", ")", ";", ...
Remove the listener active in this session. @param listenerId the id of the listener to remove
[ "Remove", "the", "listener", "active", "in", "this", "session", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/upload/CmsUploadBean.java#L627-L631
train
alkacon/opencms-core
src/org/opencms/ade/configuration/formatters/CmsFormatterBeanParser.java
CmsFormatterBeanParser.parseAttributes
private Map<String, String> parseAttributes(I_CmsXmlContentLocation formatterLoc) { Map<String, String> result = new LinkedHashMap<>(); for (I_CmsXmlContentValueLocation mappingLoc : formatterLoc.getSubValues(N_ATTRIBUTE)) { String key = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_KEY)); String value = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_VALUE)); result.put(key, value); } return Collections.unmodifiableMap(result); }
java
private Map<String, String> parseAttributes(I_CmsXmlContentLocation formatterLoc) { Map<String, String> result = new LinkedHashMap<>(); for (I_CmsXmlContentValueLocation mappingLoc : formatterLoc.getSubValues(N_ATTRIBUTE)) { String key = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_KEY)); String value = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_VALUE)); result.put(key, value); } return Collections.unmodifiableMap(result); }
[ "private", "Map", "<", "String", ",", "String", ">", "parseAttributes", "(", "I_CmsXmlContentLocation", "formatterLoc", ")", "{", "Map", "<", "String", ",", "String", ">", "result", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "for", "(", "I_CmsXmlConte...
Parses formatter attributes. @param formatterLoc the node location @return the map of formatter attributes (unmodifiable)
[ "Parses", "formatter", "attributes", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/formatters/CmsFormatterBeanParser.java#L686-L695
train
alkacon/opencms-core
src/org/opencms/ade/configuration/CmsADEManager.java
CmsADEManager.getConfiguredWorkplaceBundles
public Set<String> getConfiguredWorkplaceBundles() { CmsADEConfigData configData = internalLookupConfiguration(null, null); return configData.getConfiguredWorkplaceBundles(); }
java
public Set<String> getConfiguredWorkplaceBundles() { CmsADEConfigData configData = internalLookupConfiguration(null, null); return configData.getConfiguredWorkplaceBundles(); }
[ "public", "Set", "<", "String", ">", "getConfiguredWorkplaceBundles", "(", ")", "{", "CmsADEConfigData", "configData", "=", "internalLookupConfiguration", "(", "null", ",", "null", ")", ";", "return", "configData", ".", "getConfiguredWorkplaceBundles", "(", ")", ";"...
Returns the names of the bundles configured as workplace bundles in any module configuration. @return the names of the bundles configured as workplace bundles in any module configuration.
[ "Returns", "the", "names", "of", "the", "bundles", "configured", "as", "workplace", "bundles", "in", "any", "module", "configuration", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsADEManager.java#L366-L370
train
alkacon/opencms-core
src/org/opencms/staticexport/CmsLinkManager.java
CmsLinkManager.removeOpenCmsContext
public static String removeOpenCmsContext(final String path) { String context = OpenCms.getSystemInfo().getOpenCmsContext(); if (path.startsWith(context + "/")) { return path.substring(context.length()); } String renderPrefix = OpenCms.getStaticExportManager().getVfsPrefix(); if (path.startsWith(renderPrefix + "/")) { return path.substring(renderPrefix.length()); } return path; }
java
public static String removeOpenCmsContext(final String path) { String context = OpenCms.getSystemInfo().getOpenCmsContext(); if (path.startsWith(context + "/")) { return path.substring(context.length()); } String renderPrefix = OpenCms.getStaticExportManager().getVfsPrefix(); if (path.startsWith(renderPrefix + "/")) { return path.substring(renderPrefix.length()); } return path; }
[ "public", "static", "String", "removeOpenCmsContext", "(", "final", "String", "path", ")", "{", "String", "context", "=", "OpenCms", ".", "getSystemInfo", "(", ")", ".", "getOpenCmsContext", "(", ")", ";", "if", "(", "path", ".", "startsWith", "(", "context"...
Given a path to a VFS resource, the method removes the OpenCms context, in case the path is prefixed by that context. @param path the path where the OpenCms context should be removed @return the adjusted path
[ "Given", "a", "path", "to", "a", "VFS", "resource", "the", "method", "removes", "the", "OpenCms", "context", "in", "case", "the", "path", "is", "prefixed", "by", "that", "context", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsLinkManager.java#L276-L287
train
alkacon/opencms-core
src/org/opencms/staticexport/CmsLinkManager.java
CmsLinkManager.getPermalink
public String getPermalink(CmsObject cms, String resourceName, CmsUUID detailContentId) { String permalink = ""; try { permalink = substituteLink(cms, CmsPermalinkResourceHandler.PERMALINK_HANDLER); String id = cms.readResource(resourceName, CmsResourceFilter.ALL).getStructureId().toString(); permalink += id; if (detailContentId != null) { permalink += ":" + detailContentId; } String ext = CmsFileUtil.getExtension(resourceName); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(ext)) { permalink += ext; } CmsSite currentSite = OpenCms.getSiteManager().getCurrentSite(cms); String serverPrefix = null; if (currentSite == OpenCms.getSiteManager().getDefaultSite()) { Optional<CmsSite> siteForDefaultUri = OpenCms.getSiteManager().getSiteForDefaultUri(); if (siteForDefaultUri.isPresent()) { serverPrefix = siteForDefaultUri.get().getServerPrefix(cms, resourceName); } else { serverPrefix = OpenCms.getSiteManager().getWorkplaceServer(); } } else { serverPrefix = currentSite.getServerPrefix(cms, resourceName); } if (!permalink.startsWith(serverPrefix)) { permalink = serverPrefix + permalink; } } catch (CmsException e) { // if something wrong permalink = e.getLocalizedMessage(); if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } } return permalink; }
java
public String getPermalink(CmsObject cms, String resourceName, CmsUUID detailContentId) { String permalink = ""; try { permalink = substituteLink(cms, CmsPermalinkResourceHandler.PERMALINK_HANDLER); String id = cms.readResource(resourceName, CmsResourceFilter.ALL).getStructureId().toString(); permalink += id; if (detailContentId != null) { permalink += ":" + detailContentId; } String ext = CmsFileUtil.getExtension(resourceName); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(ext)) { permalink += ext; } CmsSite currentSite = OpenCms.getSiteManager().getCurrentSite(cms); String serverPrefix = null; if (currentSite == OpenCms.getSiteManager().getDefaultSite()) { Optional<CmsSite> siteForDefaultUri = OpenCms.getSiteManager().getSiteForDefaultUri(); if (siteForDefaultUri.isPresent()) { serverPrefix = siteForDefaultUri.get().getServerPrefix(cms, resourceName); } else { serverPrefix = OpenCms.getSiteManager().getWorkplaceServer(); } } else { serverPrefix = currentSite.getServerPrefix(cms, resourceName); } if (!permalink.startsWith(serverPrefix)) { permalink = serverPrefix + permalink; } } catch (CmsException e) { // if something wrong permalink = e.getLocalizedMessage(); if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } } return permalink; }
[ "public", "String", "getPermalink", "(", "CmsObject", "cms", ",", "String", "resourceName", ",", "CmsUUID", "detailContentId", ")", "{", "String", "permalink", "=", "\"\"", ";", "try", "{", "permalink", "=", "substituteLink", "(", "cms", ",", "CmsPermalinkResour...
Returns the perma link for the given resource and optional detail content.<p< @param cms the CMS context to use @param resourceName the page to generate the perma link for @param detailContentId the structure id of the detail content (may be null) @return the perma link
[ "Returns", "the", "perma", "link", "for", "the", "given", "resource", "and", "optional", "detail", "content", ".", "<p<" ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsLinkManager.java#L423-L461
train
alkacon/opencms-core
src/org/opencms/staticexport/CmsLinkManager.java
CmsLinkManager.getPermalinkForCurrentPage
public String getPermalinkForCurrentPage(CmsObject cms) { return getPermalink(cms, cms.getRequestContext().getUri(), cms.getRequestContext().getDetailContentId()); }
java
public String getPermalinkForCurrentPage(CmsObject cms) { return getPermalink(cms, cms.getRequestContext().getUri(), cms.getRequestContext().getDetailContentId()); }
[ "public", "String", "getPermalinkForCurrentPage", "(", "CmsObject", "cms", ")", "{", "return", "getPermalink", "(", "cms", ",", "cms", ".", "getRequestContext", "(", ")", ".", "getUri", "(", ")", ",", "cms", ".", "getRequestContext", "(", ")", ".", "getDetai...
Returns the perma link for the current page based on the URI and detail content id stored in the CmsObject passed as a parameter.<p< @param cms the CMS context to use to generate the permalink @return the permalink
[ "Returns", "the", "perma", "link", "for", "the", "current", "page", "based", "on", "the", "URI", "and", "detail", "content", "id", "stored", "in", "the", "CmsObject", "passed", "as", "a", "parameter", ".", "<p<" ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsLinkManager.java#L470-L473
train
alkacon/opencms-core
src/org/opencms/staticexport/CmsLinkManager.java
CmsLinkManager.getWorkplaceLink
public String getWorkplaceLink(CmsObject cms, String resourceName, boolean forceSecure) { String result = substituteLinkForUnknownTarget(cms, resourceName, forceSecure); return appendServerPrefix(cms, result, resourceName, true); }
java
public String getWorkplaceLink(CmsObject cms, String resourceName, boolean forceSecure) { String result = substituteLinkForUnknownTarget(cms, resourceName, forceSecure); return appendServerPrefix(cms, result, resourceName, true); }
[ "public", "String", "getWorkplaceLink", "(", "CmsObject", "cms", ",", "String", "resourceName", ",", "boolean", "forceSecure", ")", "{", "String", "result", "=", "substituteLinkForUnknownTarget", "(", "cms", ",", "resourceName", ",", "forceSecure", ")", ";", "retu...
Returns the link for the given workplace resource. This should only be used for resources under /system or /shared.<p< @param cms the current OpenCms user context @param resourceName the resource to generate the online link for @param forceSecure forces the secure server prefix @return the link for the given resource
[ "Returns", "the", "link", "for", "the", "given", "workplace", "resource", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsLinkManager.java#L599-L604
train
alkacon/opencms-core
src/org/opencms/ui/apps/dbmanager/sqlconsole/CmsSqlConsoleResultsForm.java
CmsSqlConsoleResultsForm.buildTable
private Table buildTable(CmsSqlConsoleResults results) { IndexedContainer container = new IndexedContainer(); int numCols = results.getColumns().size(); for (int c = 0; c < numCols; c++) { container.addContainerProperty(Integer.valueOf(c), results.getColumnType(c), null); } int r = 0; for (List<Object> row : results.getData()) { Item item = container.addItem(Integer.valueOf(r)); for (int c = 0; c < numCols; c++) { item.getItemProperty(Integer.valueOf(c)).setValue(row.get(c)); } r += 1; } Table table = new Table(); table.setContainerDataSource(container); for (int c = 0; c < numCols; c++) { String col = (results.getColumns().get(c)); table.setColumnHeader(Integer.valueOf(c), col); } table.setWidth("100%"); table.setHeight("100%"); table.setColumnCollapsingAllowed(true); return table; }
java
private Table buildTable(CmsSqlConsoleResults results) { IndexedContainer container = new IndexedContainer(); int numCols = results.getColumns().size(); for (int c = 0; c < numCols; c++) { container.addContainerProperty(Integer.valueOf(c), results.getColumnType(c), null); } int r = 0; for (List<Object> row : results.getData()) { Item item = container.addItem(Integer.valueOf(r)); for (int c = 0; c < numCols; c++) { item.getItemProperty(Integer.valueOf(c)).setValue(row.get(c)); } r += 1; } Table table = new Table(); table.setContainerDataSource(container); for (int c = 0; c < numCols; c++) { String col = (results.getColumns().get(c)); table.setColumnHeader(Integer.valueOf(c), col); } table.setWidth("100%"); table.setHeight("100%"); table.setColumnCollapsingAllowed(true); return table; }
[ "private", "Table", "buildTable", "(", "CmsSqlConsoleResults", "results", ")", "{", "IndexedContainer", "container", "=", "new", "IndexedContainer", "(", ")", ";", "int", "numCols", "=", "results", ".", "getColumns", "(", ")", ".", "size", "(", ")", ";", "fo...
Builds the table for the database results. @param results the database results @return the table
[ "Builds", "the", "table", "for", "the", "database", "results", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/dbmanager/sqlconsole/CmsSqlConsoleResultsForm.java#L136-L161
train
alkacon/opencms-core
src-gwt/org/opencms/ade/galleries/client/preview/ui/CmsPropertiesTab.java
CmsPropertiesTab.updateImageInfo
private void updateImageInfo() { String crop = getCrop(); String point = getPoint(); m_imageInfoDisplay.fillContent(m_info, crop, point); }
java
private void updateImageInfo() { String crop = getCrop(); String point = getPoint(); m_imageInfoDisplay.fillContent(m_info, crop, point); }
[ "private", "void", "updateImageInfo", "(", ")", "{", "String", "crop", "=", "getCrop", "(", ")", ";", "String", "point", "=", "getPoint", "(", ")", ";", "m_imageInfoDisplay", ".", "fillContent", "(", "m_info", ",", "crop", ",", "point", ")", ";", "}" ]
Updates the image information.
[ "Updates", "the", "image", "information", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/preview/ui/CmsPropertiesTab.java#L242-L247
train
alkacon/opencms-core
src/org/opencms/main/CmsShell.java
CmsShell.getTopShell
public static CmsShell getTopShell() { ArrayList<CmsShell> shells = SHELL_STACK.get(); if (shells.isEmpty()) { return null; } return shells.get(shells.size() - 1); }
java
public static CmsShell getTopShell() { ArrayList<CmsShell> shells = SHELL_STACK.get(); if (shells.isEmpty()) { return null; } return shells.get(shells.size() - 1); }
[ "public", "static", "CmsShell", "getTopShell", "(", ")", "{", "ArrayList", "<", "CmsShell", ">", "shells", "=", "SHELL_STACK", ".", "get", "(", ")", ";", "if", "(", "shells", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "...
Gets the top of thread-local shell stack, or null if it is empty. @return the top of the shell stack
[ "Gets", "the", "top", "of", "thread", "-", "local", "shell", "stack", "or", "null", "if", "it", "is", "empty", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShell.java#L581-L589
train
alkacon/opencms-core
src/org/opencms/main/CmsShell.java
CmsShell.popShell
public static void popShell() { ArrayList<CmsShell> shells = SHELL_STACK.get(); if (shells.size() > 0) { shells.remove(shells.size() - 1); } }
java
public static void popShell() { ArrayList<CmsShell> shells = SHELL_STACK.get(); if (shells.size() > 0) { shells.remove(shells.size() - 1); } }
[ "public", "static", "void", "popShell", "(", ")", "{", "ArrayList", "<", "CmsShell", ">", "shells", "=", "SHELL_STACK", ".", "get", "(", ")", ";", "if", "(", "shells", ".", "size", "(", ")", ">", "0", ")", "{", "shells", ".", "remove", "(", "shells...
Removes top of thread-local shell stack.
[ "Removes", "top", "of", "thread", "-", "local", "shell", "stack", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShell.java#L693-L700
train
alkacon/opencms-core
src/org/opencms/jsp/search/config/CmsSearchConfigurationSorting.java
CmsSearchConfigurationSorting.create
public static CmsSearchConfigurationSorting create( final String sortParam, final List<I_CmsSearchConfigurationSortOption> options, final I_CmsSearchConfigurationSortOption defaultOption) { return (null != sortParam) || ((null != options) && !options.isEmpty()) || (null != defaultOption) ? new CmsSearchConfigurationSorting(sortParam, options, defaultOption) : null; }
java
public static CmsSearchConfigurationSorting create( final String sortParam, final List<I_CmsSearchConfigurationSortOption> options, final I_CmsSearchConfigurationSortOption defaultOption) { return (null != sortParam) || ((null != options) && !options.isEmpty()) || (null != defaultOption) ? new CmsSearchConfigurationSorting(sortParam, options, defaultOption) : null; }
[ "public", "static", "CmsSearchConfigurationSorting", "create", "(", "final", "String", "sortParam", ",", "final", "List", "<", "I_CmsSearchConfigurationSortOption", ">", "options", ",", "final", "I_CmsSearchConfigurationSortOption", "defaultOption", ")", "{", "return", "(...
Creates a sort configuration iff at least one of the parameters is not null and the options list is not empty. @param sortParam The request parameter used to send the currently chosen search option. @param options The available sort options. @param defaultOption The default sort option. @return the sort configuration or null, depending on the arguments.
[ "Creates", "a", "sort", "configuration", "iff", "at", "least", "one", "of", "the", "parameters", "is", "not", "null", "and", "the", "options", "list", "is", "not", "empty", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/search/config/CmsSearchConfigurationSorting.java#L66-L74
train
alkacon/opencms-core
src/org/opencms/ui/apps/dbmanager/CmsResourceTypeStatResultList.java
CmsResourceTypeStatResultList.init
public static CmsResourceTypeStatResultList init(CmsResourceTypeStatResultList resList) { if (resList == null) { return new CmsResourceTypeStatResultList(); } resList.deleteOld(); return resList; }
java
public static CmsResourceTypeStatResultList init(CmsResourceTypeStatResultList resList) { if (resList == null) { return new CmsResourceTypeStatResultList(); } resList.deleteOld(); return resList; }
[ "public", "static", "CmsResourceTypeStatResultList", "init", "(", "CmsResourceTypeStatResultList", "resList", ")", "{", "if", "(", "resList", "==", "null", ")", "{", "return", "new", "CmsResourceTypeStatResultList", "(", ")", ";", "}", "resList", ".", "deleteOld", ...
Method to initialize the list. @param resList a given instance or null @return an instance
[ "Method", "to", "initialize", "the", "list", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/dbmanager/CmsResourceTypeStatResultList.java#L75-L83
train
alkacon/opencms-core
src/org/opencms/importexport/CmsExport.java
CmsExport.exportWithMinimalMetaData
protected boolean exportWithMinimalMetaData(String path) { String checkPath = path.startsWith("/") ? path + "/" : "/" + path + "/"; for (String p : m_parameters.getResourcesToExportWithMetaData()) { if (checkPath.startsWith(p)) { return false; } } return true; }
java
protected boolean exportWithMinimalMetaData(String path) { String checkPath = path.startsWith("/") ? path + "/" : "/" + path + "/"; for (String p : m_parameters.getResourcesToExportWithMetaData()) { if (checkPath.startsWith(p)) { return false; } } return true; }
[ "protected", "boolean", "exportWithMinimalMetaData", "(", "String", "path", ")", "{", "String", "checkPath", "=", "path", ".", "startsWith", "(", "\"/\"", ")", "?", "path", "+", "\"/\"", ":", "\"/\"", "+", "path", "+", "\"/\"", ";", "for", "(", "String", ...
Check, if the resource should be exported with minimal meta-data. This holds for resources that are not part of the export, but must be exported as super-folders. @param path export-site relative path of the resource to check. @return flag, indicating if the resource should be exported with minimal meta data.
[ "Check", "if", "the", "resource", "should", "be", "exported", "with", "minimal", "meta", "-", "data", ".", "This", "holds", "for", "resources", "that", "are", "not", "part", "of", "the", "export", "but", "must", "be", "exported", "as", "super", "-", "fol...
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsExport.java#L1365-L1374
train
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/super_src/com/google/gwt/dom/client/DOMImplWebkit.java
DOMImplWebkit.setDraggable
@Override public void setDraggable(Element elem, String draggable) { super.setDraggable(elem, draggable); if ("true".equals(draggable)) { elem.getStyle().setProperty("webkitUserDrag", "element"); } else { elem.getStyle().clearProperty("webkitUserDrag"); } }
java
@Override public void setDraggable(Element elem, String draggable) { super.setDraggable(elem, draggable); if ("true".equals(draggable)) { elem.getStyle().setProperty("webkitUserDrag", "element"); } else { elem.getStyle().clearProperty("webkitUserDrag"); } }
[ "@", "Override", "public", "void", "setDraggable", "(", "Element", "elem", ",", "String", "draggable", ")", "{", "super", ".", "setDraggable", "(", "elem", ",", "draggable", ")", ";", "if", "(", "\"true\"", ".", "equals", "(", "draggable", ")", ")", "{",...
Webkit based browsers require that we set the webkit-user-drag style attribute to make an element draggable.
[ "Webkit", "based", "browsers", "require", "that", "we", "set", "the", "webkit", "-", "user", "-", "drag", "style", "attribute", "to", "make", "an", "element", "draggable", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/super_src/com/google/gwt/dom/client/DOMImplWebkit.java#L58-L66
train
alkacon/opencms-core
src/org/opencms/ui/apps/resourcetypes/CmsNewResourceTypeDialog.java
CmsNewResourceTypeDialog.createParentXmlElements
protected void createParentXmlElements(CmsXmlContent xmlContent, String xmlPath, Locale l) { if (CmsXmlUtils.isDeepXpath(xmlPath)) { String parentPath = CmsXmlUtils.removeLastXpathElement(xmlPath); if (null == xmlContent.getValue(parentPath, l)) { createParentXmlElements(xmlContent, parentPath, l); xmlContent.addValue(m_cms, parentPath, l, CmsXmlUtils.getXpathIndexInt(parentPath) - 1); } } }
java
protected void createParentXmlElements(CmsXmlContent xmlContent, String xmlPath, Locale l) { if (CmsXmlUtils.isDeepXpath(xmlPath)) { String parentPath = CmsXmlUtils.removeLastXpathElement(xmlPath); if (null == xmlContent.getValue(parentPath, l)) { createParentXmlElements(xmlContent, parentPath, l); xmlContent.addValue(m_cms, parentPath, l, CmsXmlUtils.getXpathIndexInt(parentPath) - 1); } } }
[ "protected", "void", "createParentXmlElements", "(", "CmsXmlContent", "xmlContent", ",", "String", "xmlPath", ",", "Locale", "l", ")", "{", "if", "(", "CmsXmlUtils", ".", "isDeepXpath", "(", "xmlPath", ")", ")", "{", "String", "parentPath", "=", "CmsXmlUtils", ...
Creates the parents of nested XML elements if necessary. @param xmlContent the XML content that is edited. @param xmlPath the path of the (nested) element, for which the parents should be created @param l the locale for which the XML content is edited.
[ "Creates", "the", "parents", "of", "nested", "XML", "elements", "if", "necessary", "." ]
bc104acc75d2277df5864da939a1f2de5fdee504
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/resourcetypes/CmsNewResourceTypeDialog.java#L395-L405
train
codahale/shamir
src/main/java/com/codahale/shamir/Scheme.java
Scheme.join
public byte[] join(Map<Integer, byte[]> parts) { checkArgument(parts.size() > 0, "No parts provided"); final int[] lengths = parts.values().stream().mapToInt(v -> v.length).distinct().toArray(); checkArgument(lengths.length == 1, "Varying lengths of part values"); final byte[] secret = new byte[lengths[0]]; for (int i = 0; i < secret.length; i++) { final byte[][] points = new byte[parts.size()][2]; int j = 0; for (Map.Entry<Integer, byte[]> part : parts.entrySet()) { points[j][0] = part.getKey().byteValue(); points[j][1] = part.getValue()[i]; j++; } secret[i] = GF256.interpolate(points); } return secret; }
java
public byte[] join(Map<Integer, byte[]> parts) { checkArgument(parts.size() > 0, "No parts provided"); final int[] lengths = parts.values().stream().mapToInt(v -> v.length).distinct().toArray(); checkArgument(lengths.length == 1, "Varying lengths of part values"); final byte[] secret = new byte[lengths[0]]; for (int i = 0; i < secret.length; i++) { final byte[][] points = new byte[parts.size()][2]; int j = 0; for (Map.Entry<Integer, byte[]> part : parts.entrySet()) { points[j][0] = part.getKey().byteValue(); points[j][1] = part.getValue()[i]; j++; } secret[i] = GF256.interpolate(points); } return secret; }
[ "public", "byte", "[", "]", "join", "(", "Map", "<", "Integer", ",", "byte", "[", "]", ">", "parts", ")", "{", "checkArgument", "(", "parts", ".", "size", "(", ")", ">", "0", ",", "\"No parts provided\"", ")", ";", "final", "int", "[", "]", "length...
Joins the given parts to recover the original secret. <p><b>N.B.:</b> There is no way to determine whether or not the returned value is actually the original secret. If the parts are incorrect, or are under the threshold value used to split the secret, a random value will be returned. @param parts a map of part IDs to part values @return the original secret @throws IllegalArgumentException if {@code parts} is empty or contains values of varying lengths
[ "Joins", "the", "given", "parts", "to", "recover", "the", "original", "secret", "." ]
58b9502bc96f8749a64d9ff81b5c35f0b0dde354
https://github.com/codahale/shamir/blob/58b9502bc96f8749a64d9ff81b5c35f0b0dde354/src/main/java/com/codahale/shamir/Scheme.java#L98-L114
train
gearpump/gearpump
streaming/src/main/java/io/gearpump/streaming/javaapi/Processor.java
Processor.sink
public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) { io.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system); return new Processor(p); }
java
public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) { io.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system); return new Processor(p); }
[ "public", "static", "Processor", "<", "DataSinkTask", ">", "sink", "(", "DataSink", "dataSink", ",", "int", "parallelism", ",", "String", "description", ",", "UserConfig", "taskConf", ",", "ActorSystem", "system", ")", "{", "io", ".", "gearpump", ".", "streami...
Creates a Sink Processor @param dataSink the data sink itself @param parallelism the parallelism of this processor @param description the description for this processor @param taskConf the configuration for this processor @param system actor system @return the new created sink processor
[ "Creates", "a", "Sink", "Processor" ]
6f505aad25d5b8f54976867dbf4e752f13f9702e
https://github.com/gearpump/gearpump/blob/6f505aad25d5b8f54976867dbf4e752f13f9702e/streaming/src/main/java/io/gearpump/streaming/javaapi/Processor.java#L56-L59
train
gearpump/gearpump
streaming/src/main/java/io/gearpump/streaming/javaapi/Processor.java
Processor.source
public static Processor<DataSourceTask> source(DataSource source, int parallelism, String description, UserConfig taskConf, ActorSystem system) { io.gearpump.streaming.Processor<DataSourceTask<Object, Object>> p = DataSourceProcessor.apply(source, parallelism, description, taskConf, system); return new Processor(p); }
java
public static Processor<DataSourceTask> source(DataSource source, int parallelism, String description, UserConfig taskConf, ActorSystem system) { io.gearpump.streaming.Processor<DataSourceTask<Object, Object>> p = DataSourceProcessor.apply(source, parallelism, description, taskConf, system); return new Processor(p); }
[ "public", "static", "Processor", "<", "DataSourceTask", ">", "source", "(", "DataSource", "source", ",", "int", "parallelism", ",", "String", "description", ",", "UserConfig", "taskConf", ",", "ActorSystem", "system", ")", "{", "io", ".", "gearpump", ".", "str...
Creates a Source Processor @param source the data source itself @param parallelism the parallelism of this processor @param description the description of this processor @param taskConf the configuration of this processor @param system actor system @return the new created source processor
[ "Creates", "a", "Source", "Processor" ]
6f505aad25d5b8f54976867dbf4e752f13f9702e
https://github.com/gearpump/gearpump/blob/6f505aad25d5b8f54976867dbf4e752f13f9702e/streaming/src/main/java/io/gearpump/streaming/javaapi/Processor.java#L71-L75
train
javamonkey/beetl2.0
beetl-core/src/main/java/org/beetl/core/parser/BeetlAntlrErrorStrategy.java
BeetlAntlrErrorStrategy.recoverInline
@Override public Token recoverInline(Parser recognizer) throws RecognitionException { // SINGLE TOKEN DELETION Token matchedSymbol = singleTokenDeletion(recognizer); if (matchedSymbol != null) { // we have deleted the extra token. // now, move past ttype token as if all were ok recognizer.consume(); return matchedSymbol; } // SINGLE TOKEN INSERTION if (singleTokenInsertion(recognizer)) { return getMissingSymbol(recognizer); } // BeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR); // exception.pushToken(this.getGrammarToken(recognizer.getCurrentToken())); // throw exception; throw new InputMismatchException(recognizer); }
java
@Override public Token recoverInline(Parser recognizer) throws RecognitionException { // SINGLE TOKEN DELETION Token matchedSymbol = singleTokenDeletion(recognizer); if (matchedSymbol != null) { // we have deleted the extra token. // now, move past ttype token as if all were ok recognizer.consume(); return matchedSymbol; } // SINGLE TOKEN INSERTION if (singleTokenInsertion(recognizer)) { return getMissingSymbol(recognizer); } // BeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR); // exception.pushToken(this.getGrammarToken(recognizer.getCurrentToken())); // throw exception; throw new InputMismatchException(recognizer); }
[ "@", "Override", "public", "Token", "recoverInline", "(", "Parser", "recognizer", ")", "throws", "RecognitionException", "{", "// SINGLE TOKEN DELETION\r", "Token", "matchedSymbol", "=", "singleTokenDeletion", "(", "recognizer", ")", ";", "if", "(", "matchedSymbol", "...
Make sure we don't attempt to recover inline; if the parser successfully recovers, it won't throw an exception.
[ "Make", "sure", "we", "don", "t", "attempt", "to", "recover", "inline", ";", "if", "the", "parser", "successfully", "recovers", "it", "won", "t", "throw", "an", "exception", "." ]
f32f729ad238079df5aca6e38a3c3ba0a55c78d6
https://github.com/javamonkey/beetl2.0/blob/f32f729ad238079df5aca6e38a3c3ba0a55c78d6/beetl-core/src/main/java/org/beetl/core/parser/BeetlAntlrErrorStrategy.java#L186-L209
train
javamonkey/beetl2.0
beetl-core/src/main/java/org/beetl/core/AntlrProgramBuilder.java
AntlrProgramBuilder.parseDirectiveStatement
protected DirectiveStatement parseDirectiveStatement(DirectiveStContext node) { DirectiveStContext stContext = (DirectiveStContext) node; DirectiveExpContext direExp = stContext.directiveExp(); Token token = direExp.Identifier().getSymbol(); String directive = token.getText().toLowerCase().intern(); TerminalNode value = direExp.StringLiteral(); List<TerminalNode> idNodeList = null; DirectiveExpIDListContext directExpidLisCtx = direExp.directiveExpIDList(); if (directExpidLisCtx != null) { idNodeList = directExpidLisCtx.Identifier(); } Set<String> idList = null; DirectiveStatement ds = null; if (value != null) { String idListValue = this.getStringValue(value.getText()); idList = new HashSet(Arrays.asList(idListValue.split(","))); ds = new DirectiveStatement(directive, idList, this.getBTToken(token)); } else if (idNodeList != null) { idList = new HashSet<String>(); for (TerminalNode t : idNodeList) { idList.add(t.getText()); } ds = new DirectiveStatement(directive, idList, this.getBTToken(token)); } else { ds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token)); } if (directive.equals("dynamic")) { if (ds.getIdList().size() == 0) { data.allDynamic = true; } else { data.dynamicObjectSet = ds.getIdList(); } ds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token)); return ds; } else if (directive.equalsIgnoreCase("safe_output_open".intern())) { this.pbCtx.isSafeOutput = true; return ds; } else if (directive.equalsIgnoreCase("safe_output_close".intern())) { this.pbCtx.isSafeOutput = false; return ds; } else { return ds; } }
java
protected DirectiveStatement parseDirectiveStatement(DirectiveStContext node) { DirectiveStContext stContext = (DirectiveStContext) node; DirectiveExpContext direExp = stContext.directiveExp(); Token token = direExp.Identifier().getSymbol(); String directive = token.getText().toLowerCase().intern(); TerminalNode value = direExp.StringLiteral(); List<TerminalNode> idNodeList = null; DirectiveExpIDListContext directExpidLisCtx = direExp.directiveExpIDList(); if (directExpidLisCtx != null) { idNodeList = directExpidLisCtx.Identifier(); } Set<String> idList = null; DirectiveStatement ds = null; if (value != null) { String idListValue = this.getStringValue(value.getText()); idList = new HashSet(Arrays.asList(idListValue.split(","))); ds = new DirectiveStatement(directive, idList, this.getBTToken(token)); } else if (idNodeList != null) { idList = new HashSet<String>(); for (TerminalNode t : idNodeList) { idList.add(t.getText()); } ds = new DirectiveStatement(directive, idList, this.getBTToken(token)); } else { ds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token)); } if (directive.equals("dynamic")) { if (ds.getIdList().size() == 0) { data.allDynamic = true; } else { data.dynamicObjectSet = ds.getIdList(); } ds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token)); return ds; } else if (directive.equalsIgnoreCase("safe_output_open".intern())) { this.pbCtx.isSafeOutput = true; return ds; } else if (directive.equalsIgnoreCase("safe_output_close".intern())) { this.pbCtx.isSafeOutput = false; return ds; } else { return ds; } }
[ "protected", "DirectiveStatement", "parseDirectiveStatement", "(", "DirectiveStContext", "node", ")", "{", "DirectiveStContext", "stContext", "=", "(", "DirectiveStContext", ")", "node", ";", "DirectiveExpContext", "direExp", "=", "stContext", ".", "directiveExp", "(", ...
directive dynamic xxx,yy @param node @return
[ "directive", "dynamic", "xxx", "yy" ]
f32f729ad238079df5aca6e38a3c3ba0a55c78d6
https://github.com/javamonkey/beetl2.0/blob/f32f729ad238079df5aca6e38a3c3ba0a55c78d6/beetl-core/src/main/java/org/beetl/core/AntlrProgramBuilder.java#L852-L921
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/naming/NamingConventions.java
NamingConventions.determineNamingConvention
public static NamingConvention determineNamingConvention( TypeElement type, Iterable<ExecutableElement> methods, Messager messager, Types types) { ExecutableElement beanMethod = null; ExecutableElement prefixlessMethod = null; for (ExecutableElement method : methods) { switch (methodNameConvention(method)) { case BEAN: beanMethod = firstNonNull(beanMethod, method); break; case PREFIXLESS: prefixlessMethod = firstNonNull(prefixlessMethod, method); break; default: break; } } if (prefixlessMethod != null) { if (beanMethod != null) { messager.printMessage( ERROR, "Type contains an illegal mix of get-prefixed and unprefixed getter methods, e.g. '" + beanMethod.getSimpleName() + "' and '" + prefixlessMethod.getSimpleName() + "'", type); } return new PrefixlessConvention(messager, types); } else { return new BeanConvention(messager, types); } }
java
public static NamingConvention determineNamingConvention( TypeElement type, Iterable<ExecutableElement> methods, Messager messager, Types types) { ExecutableElement beanMethod = null; ExecutableElement prefixlessMethod = null; for (ExecutableElement method : methods) { switch (methodNameConvention(method)) { case BEAN: beanMethod = firstNonNull(beanMethod, method); break; case PREFIXLESS: prefixlessMethod = firstNonNull(prefixlessMethod, method); break; default: break; } } if (prefixlessMethod != null) { if (beanMethod != null) { messager.printMessage( ERROR, "Type contains an illegal mix of get-prefixed and unprefixed getter methods, e.g. '" + beanMethod.getSimpleName() + "' and '" + prefixlessMethod.getSimpleName() + "'", type); } return new PrefixlessConvention(messager, types); } else { return new BeanConvention(messager, types); } }
[ "public", "static", "NamingConvention", "determineNamingConvention", "(", "TypeElement", "type", ",", "Iterable", "<", "ExecutableElement", ">", "methods", ",", "Messager", "messager", ",", "Types", "types", ")", "{", "ExecutableElement", "beanMethod", "=", "null", ...
Determine whether the user has followed bean-like naming convention or not.
[ "Determine", "whether", "the", "user", "has", "followed", "bean", "-", "like", "naming", "convention", "or", "not", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/naming/NamingConventions.java#L37-L68
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/source/SourceBuilder.java
SourceBuilder.add
public SourceBuilder add(String fmt, Object... args) { TemplateApplier.withParams(args).onText(source::append).onParam(this::add).parse(fmt); return this; }
java
public SourceBuilder add(String fmt, Object... args) { TemplateApplier.withParams(args).onText(source::append).onParam(this::add).parse(fmt); return this; }
[ "public", "SourceBuilder", "add", "(", "String", "fmt", ",", "Object", "...", "args", ")", "{", "TemplateApplier", ".", "withParams", "(", "args", ")", ".", "onText", "(", "source", "::", "append", ")", ".", "onParam", "(", "this", "::", "add", ")", "....
Appends formatted text to the source. <p>Formatting supports {@code %s} and {@code %n$s}. Most args are converted according to their {@link Object#toString()} method, except that:<ul> <li> {@link Package} and {@link PackageElement} instances use their fully-qualified names (no "package " prefix). <li> {@link Class}, {@link TypeElement}, {@link DeclaredType} and {@link QualifiedName} instances use their qualified names where necessary, or shorter versions if a suitable import line can be added. <li> {@link Excerpt} instances have {@link Excerpt#addTo(SourceBuilder)} called. </ul>
[ "Appends", "formatted", "text", "to", "the", "source", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/source/SourceBuilder.java#L103-L106
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/source/SourceBuilder.java
SourceBuilder.addLine
public SourceBuilder addLine(String fmt, Object... args) { add(fmt, args); source.append(LINE_SEPARATOR); return this; }
java
public SourceBuilder addLine(String fmt, Object... args) { add(fmt, args); source.append(LINE_SEPARATOR); return this; }
[ "public", "SourceBuilder", "addLine", "(", "String", "fmt", ",", "Object", "...", "args", ")", "{", "add", "(", "fmt", ",", "args", ")", ";", "source", ".", "append", "(", "LINE_SEPARATOR", ")", ";", "return", "this", ";", "}" ]
Appends a formatted line of code to the source. <p>Formatting supports {@code %s} and {@code %n$s}. Most args are converted according to their {@link Object#toString()} method, except that:<ul> <li> {@link Package} and {@link PackageElement} instances use their fully-qualified names (no "package " prefix). <li> {@link Class}, {@link TypeElement}, {@link DeclaredType} and {@link QualifiedName} instances use their qualified names where necessary, or shorter versions if a suitable import line can be added. <li> {@link Excerpt} instances have {@link Excerpt#addTo(SourceBuilder)} called. </ul>
[ "Appends", "a", "formatted", "line", "of", "code", "to", "the", "source", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/source/SourceBuilder.java#L129-L133
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/Analyser.java
Analyser.findUnderriddenMethods
private Map<StandardMethod, UnderrideLevel> findUnderriddenMethods( Iterable<ExecutableElement> methods) { Map<StandardMethod, ExecutableElement> standardMethods = new LinkedHashMap<>(); for (ExecutableElement method : methods) { Optional<StandardMethod> standardMethod = maybeStandardMethod(method); if (standardMethod.isPresent() && isUnderride(method)) { standardMethods.put(standardMethod.get(), method); } } if (standardMethods.containsKey(StandardMethod.EQUALS) != standardMethods.containsKey(StandardMethod.HASH_CODE)) { ExecutableElement underriddenMethod = standardMethods.containsKey(StandardMethod.EQUALS) ? standardMethods.get(StandardMethod.EQUALS) : standardMethods.get(StandardMethod.HASH_CODE); messager.printMessage(ERROR, "hashCode and equals must be implemented together on FreeBuilder types", underriddenMethod); } ImmutableMap.Builder<StandardMethod, UnderrideLevel> result = ImmutableMap.builder(); for (StandardMethod standardMethod : standardMethods.keySet()) { if (standardMethods.get(standardMethod).getModifiers().contains(Modifier.FINAL)) { result.put(standardMethod, UnderrideLevel.FINAL); } else { result.put(standardMethod, UnderrideLevel.OVERRIDEABLE); } } return result.build(); }
java
private Map<StandardMethod, UnderrideLevel> findUnderriddenMethods( Iterable<ExecutableElement> methods) { Map<StandardMethod, ExecutableElement> standardMethods = new LinkedHashMap<>(); for (ExecutableElement method : methods) { Optional<StandardMethod> standardMethod = maybeStandardMethod(method); if (standardMethod.isPresent() && isUnderride(method)) { standardMethods.put(standardMethod.get(), method); } } if (standardMethods.containsKey(StandardMethod.EQUALS) != standardMethods.containsKey(StandardMethod.HASH_CODE)) { ExecutableElement underriddenMethod = standardMethods.containsKey(StandardMethod.EQUALS) ? standardMethods.get(StandardMethod.EQUALS) : standardMethods.get(StandardMethod.HASH_CODE); messager.printMessage(ERROR, "hashCode and equals must be implemented together on FreeBuilder types", underriddenMethod); } ImmutableMap.Builder<StandardMethod, UnderrideLevel> result = ImmutableMap.builder(); for (StandardMethod standardMethod : standardMethods.keySet()) { if (standardMethods.get(standardMethod).getModifiers().contains(Modifier.FINAL)) { result.put(standardMethod, UnderrideLevel.FINAL); } else { result.put(standardMethod, UnderrideLevel.OVERRIDEABLE); } } return result.build(); }
[ "private", "Map", "<", "StandardMethod", ",", "UnderrideLevel", ">", "findUnderriddenMethods", "(", "Iterable", "<", "ExecutableElement", ">", "methods", ")", "{", "Map", "<", "StandardMethod", ",", "ExecutableElement", ">", "standardMethods", "=", "new", "LinkedHas...
Find any standard methods the user has 'underridden' in their type.
[ "Find", "any", "standard", "methods", "the", "user", "has", "underridden", "in", "their", "type", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/Analyser.java#L249-L276
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/Analyser.java
Analyser.hasToBuilderMethod
private boolean hasToBuilderMethod( DeclaredType builder, boolean isExtensible, Iterable<ExecutableElement> methods) { for (ExecutableElement method : methods) { if (isToBuilderMethod(builder, method)) { if (!isExtensible) { messager.printMessage(ERROR, "No accessible no-args Builder constructor available to implement toBuilder", method); } return true; } } return false; }
java
private boolean hasToBuilderMethod( DeclaredType builder, boolean isExtensible, Iterable<ExecutableElement> methods) { for (ExecutableElement method : methods) { if (isToBuilderMethod(builder, method)) { if (!isExtensible) { messager.printMessage(ERROR, "No accessible no-args Builder constructor available to implement toBuilder", method); } return true; } } return false; }
[ "private", "boolean", "hasToBuilderMethod", "(", "DeclaredType", "builder", ",", "boolean", "isExtensible", ",", "Iterable", "<", "ExecutableElement", ">", "methods", ")", "{", "for", "(", "ExecutableElement", "method", ":", "methods", ")", "{", "if", "(", "isTo...
Find a toBuilder method, if the user has provided one.
[ "Find", "a", "toBuilder", "method", "if", "the", "user", "has", "provided", "one", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/Analyser.java#L279-L294
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/Analyser.java
Analyser.generatedBuilderSimpleName
private String generatedBuilderSimpleName(TypeElement type) { String packageName = elements.getPackageOf(type).getQualifiedName().toString(); String originalName = type.getQualifiedName().toString(); checkState(originalName.startsWith(packageName + ".")); String nameWithoutPackage = originalName.substring(packageName.length() + 1); return String.format(BUILDER_SIMPLE_NAME_TEMPLATE, nameWithoutPackage.replaceAll("\\.", "_")); }
java
private String generatedBuilderSimpleName(TypeElement type) { String packageName = elements.getPackageOf(type).getQualifiedName().toString(); String originalName = type.getQualifiedName().toString(); checkState(originalName.startsWith(packageName + ".")); String nameWithoutPackage = originalName.substring(packageName.length() + 1); return String.format(BUILDER_SIMPLE_NAME_TEMPLATE, nameWithoutPackage.replaceAll("\\.", "_")); }
[ "private", "String", "generatedBuilderSimpleName", "(", "TypeElement", "type", ")", "{", "String", "packageName", "=", "elements", ".", "getPackageOf", "(", "type", ")", ".", "getQualifiedName", "(", ")", ".", "toString", "(", ")", ";", "String", "originalName",...
Returns the simple name of the builder class that should be generated for the given type. <p>This is simply the {@link #BUILDER_SIMPLE_NAME_TEMPLATE} with the original type name substituted in. (If the original type is nested, its enclosing classes will be included, separated with underscores, to ensure uniqueness.)
[ "Returns", "the", "simple", "name", "of", "the", "builder", "class", "that", "should", "be", "generated", "for", "the", "given", "type", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/Analyser.java#L587-L593
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/ToStringGenerator.java
ToStringGenerator.addToString
public static void addToString( SourceBuilder code, Datatype datatype, Map<Property, PropertyCodeGenerator> generatorsByProperty, boolean forPartial) { String typename = (forPartial ? "partial " : "") + datatype.getType().getSimpleName(); Predicate<PropertyCodeGenerator> isOptional = generator -> { Initially initially = generator.initialState(); return (initially == Initially.OPTIONAL || (initially == Initially.REQUIRED && forPartial)); }; boolean anyOptional = generatorsByProperty.values().stream().anyMatch(isOptional); boolean allOptional = generatorsByProperty.values().stream().allMatch(isOptional) && !generatorsByProperty.isEmpty(); code.addLine("") .addLine("@%s", Override.class) .addLine("public %s toString() {", String.class); if (allOptional) { bodyWithBuilderAndSeparator(code, datatype, generatorsByProperty, typename); } else if (anyOptional) { bodyWithBuilder(code, datatype, generatorsByProperty, typename, isOptional); } else { bodyWithConcatenation(code, generatorsByProperty, typename); } code.addLine("}"); }
java
public static void addToString( SourceBuilder code, Datatype datatype, Map<Property, PropertyCodeGenerator> generatorsByProperty, boolean forPartial) { String typename = (forPartial ? "partial " : "") + datatype.getType().getSimpleName(); Predicate<PropertyCodeGenerator> isOptional = generator -> { Initially initially = generator.initialState(); return (initially == Initially.OPTIONAL || (initially == Initially.REQUIRED && forPartial)); }; boolean anyOptional = generatorsByProperty.values().stream().anyMatch(isOptional); boolean allOptional = generatorsByProperty.values().stream().allMatch(isOptional) && !generatorsByProperty.isEmpty(); code.addLine("") .addLine("@%s", Override.class) .addLine("public %s toString() {", String.class); if (allOptional) { bodyWithBuilderAndSeparator(code, datatype, generatorsByProperty, typename); } else if (anyOptional) { bodyWithBuilder(code, datatype, generatorsByProperty, typename, isOptional); } else { bodyWithConcatenation(code, generatorsByProperty, typename); } code.addLine("}"); }
[ "public", "static", "void", "addToString", "(", "SourceBuilder", "code", ",", "Datatype", "datatype", ",", "Map", "<", "Property", ",", "PropertyCodeGenerator", ">", "generatorsByProperty", ",", "boolean", "forPartial", ")", "{", "String", "typename", "=", "(", ...
Generates a toString method using concatenation or a StringBuilder.
[ "Generates", "a", "toString", "method", "using", "concatenation", "or", "a", "StringBuilder", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/ToStringGenerator.java#L23-L48
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/ToStringGenerator.java
ToStringGenerator.bodyWithConcatenation
private static void bodyWithConcatenation( SourceBuilder code, Map<Property, PropertyCodeGenerator> generatorsByProperty, String typename) { code.add(" return \"%s{", typename); String prefix = ""; for (Property property : generatorsByProperty.keySet()) { PropertyCodeGenerator generator = generatorsByProperty.get(property); code.add("%s%s=\" + %s + \"", prefix, property.getName(), (Excerpt) generator::addToStringValue); prefix = ", "; } code.add("}\";%n"); }
java
private static void bodyWithConcatenation( SourceBuilder code, Map<Property, PropertyCodeGenerator> generatorsByProperty, String typename) { code.add(" return \"%s{", typename); String prefix = ""; for (Property property : generatorsByProperty.keySet()) { PropertyCodeGenerator generator = generatorsByProperty.get(property); code.add("%s%s=\" + %s + \"", prefix, property.getName(), (Excerpt) generator::addToStringValue); prefix = ", "; } code.add("}\";%n"); }
[ "private", "static", "void", "bodyWithConcatenation", "(", "SourceBuilder", "code", ",", "Map", "<", "Property", ",", "PropertyCodeGenerator", ">", "generatorsByProperty", ",", "String", "typename", ")", "{", "code", ".", "add", "(", "\" return \\\"%s{\"", ",", "...
Generate the body of a toString method that uses plain concatenation. <p>Conventionally, we join properties with comma separators. If all of the properties are always present, this can be done with a long block of unconditional code. We could use a StringBuilder for this, but in fact the Java compiler will do this for us under the hood if we use simple string concatenation, so we use the more readable approach.
[ "Generate", "the", "body", "of", "a", "toString", "method", "that", "uses", "plain", "concatenation", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/ToStringGenerator.java#L58-L71
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/ToStringGenerator.java
ToStringGenerator.bodyWithBuilder
private static void bodyWithBuilder( SourceBuilder code, Datatype datatype, Map<Property, PropertyCodeGenerator> generatorsByProperty, String typename, Predicate<PropertyCodeGenerator> isOptional) { Variable result = new Variable("result"); code.add(" %1$s %2$s = new %1$s(\"%3$s{", StringBuilder.class, result, typename); boolean midStringLiteral = true; boolean midAppends = true; boolean prependCommas = false; PropertyCodeGenerator lastOptionalGenerator = generatorsByProperty.values() .stream() .filter(isOptional) .reduce((first, second) -> second) .get(); for (Property property : generatorsByProperty.keySet()) { PropertyCodeGenerator generator = generatorsByProperty.get(property); if (isOptional.test(generator)) { if (midStringLiteral) { code.add("\")"); } if (midAppends) { code.add(";%n "); } code.add("if ("); if (generator.initialState() == Initially.OPTIONAL) { generator.addToStringCondition(code); } else { code.add("!%s.contains(%s.%s)", UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName()); } code.add(") {%n %s.append(\"", result); if (prependCommas) { code.add(", "); } code.add("%s=\").append(%s)", property.getName(), property.getField()); if (!prependCommas) { code.add(".append(\", \")"); } code.add(";%n }%n "); if (generator.equals(lastOptionalGenerator)) { code.add("return %s.append(\"", result); midStringLiteral = true; midAppends = true; } else { midStringLiteral = false; midAppends = false; } } else { if (!midAppends) { code.add("%s", result); } if (!midStringLiteral) { code.add(".append(\""); } if (prependCommas) { code.add(", "); } code.add("%s=\").append(%s)", property.getName(), (Excerpt) generator::addToStringValue); midStringLiteral = false; midAppends = true; prependCommas = true; } } checkState(prependCommas, "Unexpected state at end of toString method"); checkState(midAppends, "Unexpected state at end of toString method"); if (!midStringLiteral) { code.add(".append(\""); } code.add("}\").toString();%n", result); }
java
private static void bodyWithBuilder( SourceBuilder code, Datatype datatype, Map<Property, PropertyCodeGenerator> generatorsByProperty, String typename, Predicate<PropertyCodeGenerator> isOptional) { Variable result = new Variable("result"); code.add(" %1$s %2$s = new %1$s(\"%3$s{", StringBuilder.class, result, typename); boolean midStringLiteral = true; boolean midAppends = true; boolean prependCommas = false; PropertyCodeGenerator lastOptionalGenerator = generatorsByProperty.values() .stream() .filter(isOptional) .reduce((first, second) -> second) .get(); for (Property property : generatorsByProperty.keySet()) { PropertyCodeGenerator generator = generatorsByProperty.get(property); if (isOptional.test(generator)) { if (midStringLiteral) { code.add("\")"); } if (midAppends) { code.add(";%n "); } code.add("if ("); if (generator.initialState() == Initially.OPTIONAL) { generator.addToStringCondition(code); } else { code.add("!%s.contains(%s.%s)", UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName()); } code.add(") {%n %s.append(\"", result); if (prependCommas) { code.add(", "); } code.add("%s=\").append(%s)", property.getName(), property.getField()); if (!prependCommas) { code.add(".append(\", \")"); } code.add(";%n }%n "); if (generator.equals(lastOptionalGenerator)) { code.add("return %s.append(\"", result); midStringLiteral = true; midAppends = true; } else { midStringLiteral = false; midAppends = false; } } else { if (!midAppends) { code.add("%s", result); } if (!midStringLiteral) { code.add(".append(\""); } if (prependCommas) { code.add(", "); } code.add("%s=\").append(%s)", property.getName(), (Excerpt) generator::addToStringValue); midStringLiteral = false; midAppends = true; prependCommas = true; } } checkState(prependCommas, "Unexpected state at end of toString method"); checkState(midAppends, "Unexpected state at end of toString method"); if (!midStringLiteral) { code.add(".append(\""); } code.add("}\").toString();%n", result); }
[ "private", "static", "void", "bodyWithBuilder", "(", "SourceBuilder", "code", ",", "Datatype", "datatype", ",", "Map", "<", "Property", ",", "PropertyCodeGenerator", ">", "generatorsByProperty", ",", "String", "typename", ",", "Predicate", "<", "PropertyCodeGenerator"...
Generates the body of a toString method that uses a StringBuilder. <p>Conventionally, we join properties with comma separators. If all of the properties are optional, we have no choice but to track the separators at runtime, but if any of them will always be present, we can actually do the hard work at compile time. Specifically, we can pick the first such and output it without a comma; any property before it will have a comma <em>appended</em>, and any property after it will have a comma <em>prepended</em>. This gives us the right number of commas in the right places in all circumstances. <p>As well as keeping track of whether we are <b>prepending commas</b> yet (initially false), we also keep track of whether we have just finished an if-then block for an optional property, or if we are in the <b>middle of an append chain</b>, and if so, whether we are in the <b>middle of a string literal</b>. This lets us output the fewest literals and statements, much as a mildly compulsive programmer would when writing the same code.
[ "Generates", "the", "body", "of", "a", "toString", "method", "that", "uses", "a", "StringBuilder", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/ToStringGenerator.java#L89-L164
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/ToStringGenerator.java
ToStringGenerator.bodyWithBuilderAndSeparator
private static void bodyWithBuilderAndSeparator( SourceBuilder code, Datatype datatype, Map<Property, PropertyCodeGenerator> generatorsByProperty, String typename) { Variable result = new Variable("result"); Variable separator = new Variable("separator"); code.addLine(" %1$s %2$s = new %1$s(\"%3$s{\");", StringBuilder.class, result, typename); if (generatorsByProperty.size() > 1) { // If there's a single property, we don't actually use the separator variable code.addLine(" %s %s = \"\";", String.class, separator); } Property first = generatorsByProperty.keySet().iterator().next(); Property last = getLast(generatorsByProperty.keySet()); for (Property property : generatorsByProperty.keySet()) { PropertyCodeGenerator generator = generatorsByProperty.get(property); switch (generator.initialState()) { case HAS_DEFAULT: throw new RuntimeException("Internal error: unexpected default field"); case OPTIONAL: code.addLine(" if (%s) {", (Excerpt) generator::addToStringCondition); break; case REQUIRED: code.addLine(" if (!%s.contains(%s.%s)) {", UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName()); break; } code.add(" ").add(result); if (property != first) { code.add(".append(%s)", separator); } code.add(".append(\"%s=\").append(%s)", property.getName(), (Excerpt) generator::addToStringValue); if (property != last) { code.add(";%n %s = \", \"", separator); } code.add(";%n }%n"); } code.addLine(" return %s.append(\"}\").toString();", result); }
java
private static void bodyWithBuilderAndSeparator( SourceBuilder code, Datatype datatype, Map<Property, PropertyCodeGenerator> generatorsByProperty, String typename) { Variable result = new Variable("result"); Variable separator = new Variable("separator"); code.addLine(" %1$s %2$s = new %1$s(\"%3$s{\");", StringBuilder.class, result, typename); if (generatorsByProperty.size() > 1) { // If there's a single property, we don't actually use the separator variable code.addLine(" %s %s = \"\";", String.class, separator); } Property first = generatorsByProperty.keySet().iterator().next(); Property last = getLast(generatorsByProperty.keySet()); for (Property property : generatorsByProperty.keySet()) { PropertyCodeGenerator generator = generatorsByProperty.get(property); switch (generator.initialState()) { case HAS_DEFAULT: throw new RuntimeException("Internal error: unexpected default field"); case OPTIONAL: code.addLine(" if (%s) {", (Excerpt) generator::addToStringCondition); break; case REQUIRED: code.addLine(" if (!%s.contains(%s.%s)) {", UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName()); break; } code.add(" ").add(result); if (property != first) { code.add(".append(%s)", separator); } code.add(".append(\"%s=\").append(%s)", property.getName(), (Excerpt) generator::addToStringValue); if (property != last) { code.add(";%n %s = \", \"", separator); } code.add(";%n }%n"); } code.addLine(" return %s.append(\"}\").toString();", result); }
[ "private", "static", "void", "bodyWithBuilderAndSeparator", "(", "SourceBuilder", "code", ",", "Datatype", "datatype", ",", "Map", "<", "Property", ",", "PropertyCodeGenerator", ">", "generatorsByProperty", ",", "String", "typename", ")", "{", "Variable", "result", ...
Generates the body of a toString method that uses a StringBuilder and a separator variable. <p>Conventionally, we join properties with comma separators. If all of the properties are optional, we have no choice but to track the separators at runtime, as apart from the first one, all properties will need to have a comma prepended. We could do this with a boolean, maybe called "separatorNeeded", or "firstValueOutput", but then we need either a ternary operator or an extra nested if block. More readable is to use an initially-empty "separator" string, which has a comma placed in it once the first value is written. <p>For extra tidiness, we note that the first if block need not try writing the separator (it is always empty), and the last one need not update it (it will not be used again).
[ "Generates", "the", "body", "of", "a", "toString", "method", "that", "uses", "a", "StringBuilder", "and", "a", "separator", "variable", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/ToStringGenerator.java#L179-L222
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/source/LazyName.java
LazyName.addLazyDefinitions
public static void addLazyDefinitions(SourceBuilder code) { Set<Declaration> defined = new HashSet<>(); // Definitions may lazily declare new names; ensure we add them all List<Declaration> declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList()); while (!defined.containsAll(declarations)) { for (Declaration declaration : declarations) { if (defined.add(declaration)) { code.add(code.scope().get(declaration).definition); } } declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList()); } }
java
public static void addLazyDefinitions(SourceBuilder code) { Set<Declaration> defined = new HashSet<>(); // Definitions may lazily declare new names; ensure we add them all List<Declaration> declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList()); while (!defined.containsAll(declarations)) { for (Declaration declaration : declarations) { if (defined.add(declaration)) { code.add(code.scope().get(declaration).definition); } } declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList()); } }
[ "public", "static", "void", "addLazyDefinitions", "(", "SourceBuilder", "code", ")", "{", "Set", "<", "Declaration", ">", "defined", "=", "new", "HashSet", "<>", "(", ")", ";", "// Definitions may lazily declare new names; ensure we add them all", "List", "<", "Declar...
Finds all lazily-declared classes and methods and adds their definitions to the source.
[ "Finds", "all", "lazily", "-", "declared", "classes", "and", "methods", "and", "adds", "their", "definitions", "to", "the", "source", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/source/LazyName.java#L31-L45
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/property/PropertyCodeGenerator.java
PropertyCodeGenerator.addPartialFieldAssignment
public void addPartialFieldAssignment( SourceBuilder code, Excerpt finalField, String builder) { addFinalFieldAssignment(code, finalField, builder); }
java
public void addPartialFieldAssignment( SourceBuilder code, Excerpt finalField, String builder) { addFinalFieldAssignment(code, finalField, builder); }
[ "public", "void", "addPartialFieldAssignment", "(", "SourceBuilder", "code", ",", "Excerpt", "finalField", ",", "String", "builder", ")", "{", "addFinalFieldAssignment", "(", "code", ",", "finalField", ",", "builder", ")", ";", "}" ]
Add the final assignment of the property to the partial value object's source code.
[ "Add", "the", "final", "assignment", "of", "the", "property", "to", "the", "partial", "value", "object", "s", "source", "code", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/property/PropertyCodeGenerator.java#L151-L154
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/property/MergeAction.java
MergeAction.addActionsTo
public static void addActionsTo( SourceBuilder code, Set<MergeAction> mergeActions, boolean forBuilder) { SetMultimap<String, String> nounsByVerb = TreeMultimap.create(); mergeActions.forEach(mergeAction -> { if (forBuilder || !mergeAction.builderOnly) { nounsByVerb.put(mergeAction.verb, mergeAction.noun); } }); List<String> verbs = ImmutableList.copyOf(nounsByVerb.keySet()); String lastVerb = getLast(verbs, null); for (String verb : nounsByVerb.keySet()) { code.add(", %s%s", (verbs.size() > 1 && verb.equals(lastVerb)) ? "and " : "", verb); List<String> nouns = ImmutableList.copyOf(nounsByVerb.get(verb)); for (int i = 0; i < nouns.size(); ++i) { String separator = (i == 0) ? "" : (i == nouns.size() - 1) ? " and" : ","; code.add("%s %s", separator, nouns.get(i)); } } }
java
public static void addActionsTo( SourceBuilder code, Set<MergeAction> mergeActions, boolean forBuilder) { SetMultimap<String, String> nounsByVerb = TreeMultimap.create(); mergeActions.forEach(mergeAction -> { if (forBuilder || !mergeAction.builderOnly) { nounsByVerb.put(mergeAction.verb, mergeAction.noun); } }); List<String> verbs = ImmutableList.copyOf(nounsByVerb.keySet()); String lastVerb = getLast(verbs, null); for (String verb : nounsByVerb.keySet()) { code.add(", %s%s", (verbs.size() > 1 && verb.equals(lastVerb)) ? "and " : "", verb); List<String> nouns = ImmutableList.copyOf(nounsByVerb.get(verb)); for (int i = 0; i < nouns.size(); ++i) { String separator = (i == 0) ? "" : (i == nouns.size() - 1) ? " and" : ","; code.add("%s %s", separator, nouns.get(i)); } } }
[ "public", "static", "void", "addActionsTo", "(", "SourceBuilder", "code", ",", "Set", "<", "MergeAction", ">", "mergeActions", ",", "boolean", "forBuilder", ")", "{", "SetMultimap", "<", "String", ",", "String", ">", "nounsByVerb", "=", "TreeMultimap", ".", "c...
Emits a sentence fragment combining all the merge actions.
[ "Emits", "a", "sentence", "fragment", "combining", "all", "the", "merge", "actions", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/property/MergeAction.java#L39-L59
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/Declarations.java
Declarations.upcastToGeneratedBuilder
public static Variable upcastToGeneratedBuilder( SourceBuilder code, Datatype datatype, String builder) { return code.scope().computeIfAbsent(Declaration.UPCAST, () -> { Variable base = new Variable("base"); code.addLine(UPCAST_COMMENT) .addLine("%s %s = %s;", datatype.getGeneratedBuilder(), base, builder); return base; }); }
java
public static Variable upcastToGeneratedBuilder( SourceBuilder code, Datatype datatype, String builder) { return code.scope().computeIfAbsent(Declaration.UPCAST, () -> { Variable base = new Variable("base"); code.addLine(UPCAST_COMMENT) .addLine("%s %s = %s;", datatype.getGeneratedBuilder(), base, builder); return base; }); }
[ "public", "static", "Variable", "upcastToGeneratedBuilder", "(", "SourceBuilder", "code", ",", "Datatype", "datatype", ",", "String", "builder", ")", "{", "return", "code", ".", "scope", "(", ")", ".", "computeIfAbsent", "(", "Declaration", ".", "UPCAST", ",", ...
Upcasts a Builder instance to the generated superclass, to allow access to private fields. <p>Reuses an existing upcast instance if one was already declared in this scope. @param code the {@link SourceBuilder} to add the declaration to @param datatype metadata about the user type the builder is being generated for @param builder the Builder instance to upcast @returns a variable holding the upcasted instance
[ "Upcasts", "a", "Builder", "instance", "to", "the", "generated", "superclass", "to", "allow", "access", "to", "private", "fields", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/Declarations.java#L35-L43
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/Declarations.java
Declarations.freshBuilder
public static Optional<Variable> freshBuilder(SourceBuilder code, Datatype datatype) { if (!datatype.getBuilderFactory().isPresent()) { return Optional.empty(); } return Optional.of(code.scope().computeIfAbsent(Declaration.FRESH_BUILDER, () -> { Variable defaults = new Variable("defaults"); code.addLine("%s %s = %s;", datatype.getGeneratedBuilder(), defaults, datatype.getBuilderFactory().get() .newBuilder(datatype.getBuilder(), TypeInference.INFERRED_TYPES)); return defaults; })); }
java
public static Optional<Variable> freshBuilder(SourceBuilder code, Datatype datatype) { if (!datatype.getBuilderFactory().isPresent()) { return Optional.empty(); } return Optional.of(code.scope().computeIfAbsent(Declaration.FRESH_BUILDER, () -> { Variable defaults = new Variable("defaults"); code.addLine("%s %s = %s;", datatype.getGeneratedBuilder(), defaults, datatype.getBuilderFactory().get() .newBuilder(datatype.getBuilder(), TypeInference.INFERRED_TYPES)); return defaults; })); }
[ "public", "static", "Optional", "<", "Variable", ">", "freshBuilder", "(", "SourceBuilder", "code", ",", "Datatype", "datatype", ")", "{", "if", "(", "!", "datatype", ".", "getBuilderFactory", "(", ")", ".", "isPresent", "(", ")", ")", "{", "return", "Opti...
Declares a fresh Builder to copy default property values from. <p>Reuses an existing fresh Builder instance if one was already declared in this scope. @returns a variable holding a fresh Builder, if a no-args factory method is available to create one with
[ "Declares", "a", "fresh", "Builder", "to", "copy", "default", "property", "values", "from", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/Declarations.java#L53-L66
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/source/Type.java
Type.javadocMethodLink
public JavadocLink javadocMethodLink(String memberName, Type... types) { return new JavadocLink("%s#%s(%s)", getQualifiedName(), memberName, (Excerpt) code -> { String separator = ""; for (Type type : types) { code.add("%s%s", separator, type.getQualifiedName()); separator = ", "; } }); }
java
public JavadocLink javadocMethodLink(String memberName, Type... types) { return new JavadocLink("%s#%s(%s)", getQualifiedName(), memberName, (Excerpt) code -> { String separator = ""; for (Type type : types) { code.add("%s%s", separator, type.getQualifiedName()); separator = ", "; } }); }
[ "public", "JavadocLink", "javadocMethodLink", "(", "String", "memberName", ",", "Type", "...", "types", ")", "{", "return", "new", "JavadocLink", "(", "\"%s#%s(%s)\"", ",", "getQualifiedName", "(", ")", ",", "memberName", ",", "(", "Excerpt", ")", "code", "->"...
Returns a source excerpt of a JavaDoc link to a method on this type.
[ "Returns", "a", "source", "excerpt", "of", "a", "JavaDoc", "link", "to", "a", "method", "on", "this", "type", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/source/Type.java#L117-L128
train
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/source/Type.java
Type.typeParameters
public Excerpt typeParameters() { if (getTypeParameters().isEmpty()) { return Excerpts.EMPTY; } else { return Excerpts.add("<%s>", Excerpts.join(", ", getTypeParameters())); } }
java
public Excerpt typeParameters() { if (getTypeParameters().isEmpty()) { return Excerpts.EMPTY; } else { return Excerpts.add("<%s>", Excerpts.join(", ", getTypeParameters())); } }
[ "public", "Excerpt", "typeParameters", "(", ")", "{", "if", "(", "getTypeParameters", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "Excerpts", ".", "EMPTY", ";", "}", "else", "{", "return", "Excerpts", ".", "add", "(", "\"<%s>\"", ",", "Exce...
Returns a source excerpt of the type parameters of this type, including angle brackets. Always an empty string if the type class is not generic. <p>e.g. {@code <N, C>}
[ "Returns", "a", "source", "excerpt", "of", "the", "type", "parameters", "of", "this", "type", "including", "angle", "brackets", ".", "Always", "an", "empty", "string", "if", "the", "type", "class", "is", "not", "generic", "." ]
d5a222f90648aece135da4b971c55a60afe8649c
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/source/Type.java#L136-L142
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/rule/AbstractRule.java
AbstractRule.createViolation
protected Violation createViolation(Integer lineNumber, String sourceLine, String message) { Violation violation = new Violation(); violation.setRule(this); violation.setSourceLine(sourceLine); violation.setLineNumber(lineNumber); violation.setMessage(message); return violation; }
java
protected Violation createViolation(Integer lineNumber, String sourceLine, String message) { Violation violation = new Violation(); violation.setRule(this); violation.setSourceLine(sourceLine); violation.setLineNumber(lineNumber); violation.setMessage(message); return violation; }
[ "protected", "Violation", "createViolation", "(", "Integer", "lineNumber", ",", "String", "sourceLine", ",", "String", "message", ")", "{", "Violation", "violation", "=", "new", "Violation", "(", ")", ";", "violation", ".", "setRule", "(", "this", ")", ";", ...
Create and return a new Violation for this rule and the specified values @param lineNumber - the line number for the violation; may be null @param sourceLine - the source line for the violation; may be null @param message - the message for the violation; may be null @return a new Violation object
[ "Create", "and", "return", "a", "new", "Violation", "for", "this", "rule", "and", "the", "specified", "values" ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/rule/AbstractRule.java#L195-L202
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/rule/AbstractRule.java
AbstractRule.createViolation
protected Violation createViolation(SourceCode sourceCode, ASTNode node, String message) { String sourceLine = sourceCode.line(node.getLineNumber()-1); return createViolation(node.getLineNumber(), sourceLine, message); }
java
protected Violation createViolation(SourceCode sourceCode, ASTNode node, String message) { String sourceLine = sourceCode.line(node.getLineNumber()-1); return createViolation(node.getLineNumber(), sourceLine, message); }
[ "protected", "Violation", "createViolation", "(", "SourceCode", "sourceCode", ",", "ASTNode", "node", ",", "String", "message", ")", "{", "String", "sourceLine", "=", "sourceCode", ".", "line", "(", "node", ".", "getLineNumber", "(", ")", "-", "1", ")", ";",...
Create a new Violation for the AST node. @param sourceCode - the SourceCode @param node - the Groovy AST Node @param message - the message for the violation; defaults to null
[ "Create", "a", "new", "Violation", "for", "the", "AST", "node", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/rule/AbstractRule.java#L210-L213
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/rule/AbstractRule.java
AbstractRule.createViolationForImport
protected Violation createViolationForImport(SourceCode sourceCode, ImportNode importNode, String message) { Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, importNode); Violation violation = new Violation(); violation.setRule(this); violation.setSourceLine((String) importInfo.get("sourceLine")); violation.setLineNumber((Integer) importInfo.get("lineNumber")); violation.setMessage(message); return violation; }
java
protected Violation createViolationForImport(SourceCode sourceCode, ImportNode importNode, String message) { Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, importNode); Violation violation = new Violation(); violation.setRule(this); violation.setSourceLine((String) importInfo.get("sourceLine")); violation.setLineNumber((Integer) importInfo.get("lineNumber")); violation.setMessage(message); return violation; }
[ "protected", "Violation", "createViolationForImport", "(", "SourceCode", "sourceCode", ",", "ImportNode", "importNode", ",", "String", "message", ")", "{", "Map", "importInfo", "=", "ImportUtil", ".", "sourceLineAndNumberForImport", "(", "sourceCode", ",", "importNode",...
Create and return a new Violation for this rule and the specified import @param sourceCode - the SourceCode @param importNode - the ImportNode for the import triggering the violation @return a new Violation object
[ "Create", "and", "return", "a", "new", "Violation", "for", "this", "rule", "and", "the", "specified", "import" ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/rule/AbstractRule.java#L221-L229
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/rule/AbstractRule.java
AbstractRule.createViolationForImport
protected Violation createViolationForImport(SourceCode sourceCode, String className, String alias, String violationMessage) { Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, className, alias); Violation violation = new Violation(); violation.setRule(this); violation.setSourceLine((String) importInfo.get("sourceLine")); violation.setLineNumber((Integer) importInfo.get("lineNumber")); violation.setMessage(violationMessage); return violation; }
java
protected Violation createViolationForImport(SourceCode sourceCode, String className, String alias, String violationMessage) { Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, className, alias); Violation violation = new Violation(); violation.setRule(this); violation.setSourceLine((String) importInfo.get("sourceLine")); violation.setLineNumber((Integer) importInfo.get("lineNumber")); violation.setMessage(violationMessage); return violation; }
[ "protected", "Violation", "createViolationForImport", "(", "SourceCode", "sourceCode", ",", "String", "className", ",", "String", "alias", ",", "String", "violationMessage", ")", "{", "Map", "importInfo", "=", "ImportUtil", ".", "sourceLineAndNumberForImport", "(", "s...
Create and return a new Violation for this rule and the specified import className and alias @param sourceCode - the SourceCode @param className - the class name (as specified within the import statement) @param alias - the alias for the import statement @param violationMessage - the violation message; may be null @return a new Violation object
[ "Create", "and", "return", "a", "new", "Violation", "for", "this", "rule", "and", "the", "specified", "import", "className", "and", "alias" ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/rule/AbstractRule.java#L239-L247
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/rule/AbstractAstVisitorRule.java
AbstractAstVisitorRule.shouldApplyThisRuleTo
protected boolean shouldApplyThisRuleTo(ClassNode classNode) { // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns boolean shouldApply = true; String applyTo = getApplyToClassNames(); String doNotApplyTo = getDoNotApplyToClassNames(); if (applyTo != null && applyTo.length() > 0) { WildcardPattern pattern = new WildcardPattern(applyTo, true); shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName()); } if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) { WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true); shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName()); } return shouldApply; }
java
protected boolean shouldApplyThisRuleTo(ClassNode classNode) { // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns boolean shouldApply = true; String applyTo = getApplyToClassNames(); String doNotApplyTo = getDoNotApplyToClassNames(); if (applyTo != null && applyTo.length() > 0) { WildcardPattern pattern = new WildcardPattern(applyTo, true); shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName()); } if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) { WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true); shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName()); } return shouldApply; }
[ "protected", "boolean", "shouldApplyThisRuleTo", "(", "ClassNode", "classNode", ")", "{", "// TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r", "boolean", "shouldApply", "=", "true", ";", "String", "applyTo", "=", "getApplyToClassNames", "(", ")", ...
Return true if this rule should be applied for the specified ClassNode, based on the configuration of this rule. @param classNode - the ClassNode @return true if this rule should be applied for the specified ClassNode
[ "Return", "true", "if", "this", "rule", "should", "be", "applied", "for", "the", "specified", "ClassNode", "based", "on", "the", "configuration", "of", "this", "rule", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/rule/AbstractAstVisitorRule.java#L121-L139
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/ant/AntFileSetSourceAnalyzer.java
AntFileSetSourceAnalyzer.analyze
public Results analyze(RuleSet ruleSet) { long startTime = System.currentTimeMillis(); DirectoryResults reportResults = new DirectoryResults(); int numThreads = Runtime.getRuntime().availableProcessors() - 1; numThreads = numThreads > 0 ? numThreads : 1; ExecutorService pool = Executors.newFixedThreadPool(numThreads); for (FileSet fileSet : fileSets) { processFileSet(fileSet, ruleSet, pool); } pool.shutdown(); try { boolean completed = pool.awaitTermination(POOL_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!completed) { throw new IllegalStateException("Thread Pool terminated before comp<FileResults>letion"); } } catch (InterruptedException e) { throw new IllegalStateException("Thread Pool interrupted before completion"); } addDirectoryResults(reportResults); LOG.info("Analysis time=" + (System.currentTimeMillis() - startTime) + "ms"); return reportResults; }
java
public Results analyze(RuleSet ruleSet) { long startTime = System.currentTimeMillis(); DirectoryResults reportResults = new DirectoryResults(); int numThreads = Runtime.getRuntime().availableProcessors() - 1; numThreads = numThreads > 0 ? numThreads : 1; ExecutorService pool = Executors.newFixedThreadPool(numThreads); for (FileSet fileSet : fileSets) { processFileSet(fileSet, ruleSet, pool); } pool.shutdown(); try { boolean completed = pool.awaitTermination(POOL_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!completed) { throw new IllegalStateException("Thread Pool terminated before comp<FileResults>letion"); } } catch (InterruptedException e) { throw new IllegalStateException("Thread Pool interrupted before completion"); } addDirectoryResults(reportResults); LOG.info("Analysis time=" + (System.currentTimeMillis() - startTime) + "ms"); return reportResults; }
[ "public", "Results", "analyze", "(", "RuleSet", "ruleSet", ")", "{", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "DirectoryResults", "reportResults", "=", "new", "DirectoryResults", "(", ")", ";", "int", "numThreads", "=", "Run...
Analyze all source code using the specified RuleSet and return the report results. @param ruleSet - the RuleSet to apply to each source component; must not be null. @return the results from applying the RuleSet to all of the source
[ "Analyze", "all", "source", "code", "using", "the", "specified", "RuleSet", "and", "return", "the", "report", "results", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/ant/AntFileSetSourceAnalyzer.java#L95-L122
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isPredefinedConstant
private static boolean isPredefinedConstant(Expression expression) { if (expression instanceof PropertyExpression) { Expression object = ((PropertyExpression) expression).getObjectExpression(); Expression property = ((PropertyExpression) expression).getProperty(); if (object instanceof VariableExpression) { List<String> predefinedConstantNames = PREDEFINED_CONSTANTS.get(((VariableExpression) object).getName()); if (predefinedConstantNames != null && predefinedConstantNames.contains(property.getText())) { return true; } } } return false; }
java
private static boolean isPredefinedConstant(Expression expression) { if (expression instanceof PropertyExpression) { Expression object = ((PropertyExpression) expression).getObjectExpression(); Expression property = ((PropertyExpression) expression).getProperty(); if (object instanceof VariableExpression) { List<String> predefinedConstantNames = PREDEFINED_CONSTANTS.get(((VariableExpression) object).getName()); if (predefinedConstantNames != null && predefinedConstantNames.contains(property.getText())) { return true; } } } return false; }
[ "private", "static", "boolean", "isPredefinedConstant", "(", "Expression", "expression", ")", "{", "if", "(", "expression", "instanceof", "PropertyExpression", ")", "{", "Expression", "object", "=", "(", "(", "PropertyExpression", ")", "expression", ")", ".", "get...
Tells you if the expression is a predefined constant like TRUE or FALSE. @param expression any expression @return as described
[ "Tells", "you", "if", "the", "expression", "is", "a", "predefined", "constant", "like", "TRUE", "or", "FALSE", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L85-L98
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isMapLiteralWithOnlyConstantValues
public static boolean isMapLiteralWithOnlyConstantValues(Expression expression) { if (expression instanceof MapExpression) { List<MapEntryExpression> entries = ((MapExpression) expression).getMapEntryExpressions(); for (MapEntryExpression entry : entries) { if (!isConstantOrConstantLiteral(entry.getKeyExpression()) || !isConstantOrConstantLiteral(entry.getValueExpression())) { return false; } } return true; } return false; }
java
public static boolean isMapLiteralWithOnlyConstantValues(Expression expression) { if (expression instanceof MapExpression) { List<MapEntryExpression> entries = ((MapExpression) expression).getMapEntryExpressions(); for (MapEntryExpression entry : entries) { if (!isConstantOrConstantLiteral(entry.getKeyExpression()) || !isConstantOrConstantLiteral(entry.getValueExpression())) { return false; } } return true; } return false; }
[ "public", "static", "boolean", "isMapLiteralWithOnlyConstantValues", "(", "Expression", "expression", ")", "{", "if", "(", "expression", "instanceof", "MapExpression", ")", "{", "List", "<", "MapEntryExpression", ">", "entries", "=", "(", "(", "MapExpression", ")", ...
Returns true if a Map literal that contains only entries where both key and value are constants. @param expression - any expression
[ "Returns", "true", "if", "a", "Map", "literal", "that", "contains", "only", "entries", "where", "both", "key", "and", "value", "are", "constants", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L116-L128
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isListLiteralWithOnlyConstantValues
public static boolean isListLiteralWithOnlyConstantValues(Expression expression) { if (expression instanceof ListExpression) { List<Expression> expressions = ((ListExpression) expression).getExpressions(); for (Expression e : expressions) { if (!isConstantOrConstantLiteral(e)) { return false; } } return true; } return false; }
java
public static boolean isListLiteralWithOnlyConstantValues(Expression expression) { if (expression instanceof ListExpression) { List<Expression> expressions = ((ListExpression) expression).getExpressions(); for (Expression e : expressions) { if (!isConstantOrConstantLiteral(e)) { return false; } } return true; } return false; }
[ "public", "static", "boolean", "isListLiteralWithOnlyConstantValues", "(", "Expression", "expression", ")", "{", "if", "(", "expression", "instanceof", "ListExpression", ")", "{", "List", "<", "Expression", ">", "expressions", "=", "(", "(", "ListExpression", ")", ...
Returns true if a List literal that contains only entries that are constants. @param expression - any expression
[ "Returns", "true", "if", "a", "List", "literal", "that", "contains", "only", "entries", "that", "are", "constants", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L134-L145
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isConstant
public static boolean isConstant(Expression expression, Object expected) { return expression instanceof ConstantExpression && expected.equals(((ConstantExpression) expression).getValue()); }
java
public static boolean isConstant(Expression expression, Object expected) { return expression instanceof ConstantExpression && expected.equals(((ConstantExpression) expression).getValue()); }
[ "public", "static", "boolean", "isConstant", "(", "Expression", "expression", ",", "Object", "expected", ")", "{", "return", "expression", "instanceof", "ConstantExpression", "&&", "expected", ".", "equals", "(", "(", "(", "ConstantExpression", ")", "expression", ...
Tells you if an expression is the expected constant. @param expression any expression @param expected the expected int or String @return as described
[ "Tells", "you", "if", "an", "expression", "is", "the", "expected", "constant", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L156-L158
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.getMethodArguments
public static List<? extends Expression> getMethodArguments(ASTNode methodCall) { if (methodCall instanceof ConstructorCallExpression) { return extractExpressions(((ConstructorCallExpression) methodCall).getArguments()); } else if (methodCall instanceof MethodCallExpression) { return extractExpressions(((MethodCallExpression) methodCall).getArguments()); } else if (methodCall instanceof StaticMethodCallExpression) { return extractExpressions(((StaticMethodCallExpression) methodCall).getArguments()); } else if (respondsTo(methodCall, "getArguments")) { throw new RuntimeException(); // TODO: remove, should never happen } return new ArrayList<Expression>(); }
java
public static List<? extends Expression> getMethodArguments(ASTNode methodCall) { if (methodCall instanceof ConstructorCallExpression) { return extractExpressions(((ConstructorCallExpression) methodCall).getArguments()); } else if (methodCall instanceof MethodCallExpression) { return extractExpressions(((MethodCallExpression) methodCall).getArguments()); } else if (methodCall instanceof StaticMethodCallExpression) { return extractExpressions(((StaticMethodCallExpression) methodCall).getArguments()); } else if (respondsTo(methodCall, "getArguments")) { throw new RuntimeException(); // TODO: remove, should never happen } return new ArrayList<Expression>(); }
[ "public", "static", "List", "<", "?", "extends", "Expression", ">", "getMethodArguments", "(", "ASTNode", "methodCall", ")", "{", "if", "(", "methodCall", "instanceof", "ConstructorCallExpression", ")", "{", "return", "extractExpressions", "(", "(", "(", "Construc...
Return the List of Arguments for the specified MethodCallExpression or a ConstructorCallExpression. The returned List contains either ConstantExpression or MapEntryExpression objects. @param methodCall - the AST MethodCallExpression or ConstructorCalLExpression @return the List of argument objects
[ "Return", "the", "List", "of", "Arguments", "for", "the", "specified", "MethodCallExpression", "or", "a", "ConstructorCallExpression", ".", "The", "returned", "List", "contains", "either", "ConstantExpression", "or", "MapEntryExpression", "objects", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L226-L237
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isMethodNamed
public static boolean isMethodNamed(MethodCallExpression methodCall, String methodNamePattern, Integer numArguments) { Expression method = methodCall.getMethod(); // !important: performance enhancement boolean IS_NAME_MATCH = false; if (method instanceof ConstantExpression) { if (((ConstantExpression) method).getValue() instanceof String) { IS_NAME_MATCH = ((String)((ConstantExpression) method).getValue()).matches(methodNamePattern); } } if (IS_NAME_MATCH && numArguments != null) { return AstUtil.getMethodArguments(methodCall).size() == numArguments; } return IS_NAME_MATCH; }
java
public static boolean isMethodNamed(MethodCallExpression methodCall, String methodNamePattern, Integer numArguments) { Expression method = methodCall.getMethod(); // !important: performance enhancement boolean IS_NAME_MATCH = false; if (method instanceof ConstantExpression) { if (((ConstantExpression) method).getValue() instanceof String) { IS_NAME_MATCH = ((String)((ConstantExpression) method).getValue()).matches(methodNamePattern); } } if (IS_NAME_MATCH && numArguments != null) { return AstUtil.getMethodArguments(methodCall).size() == numArguments; } return IS_NAME_MATCH; }
[ "public", "static", "boolean", "isMethodNamed", "(", "MethodCallExpression", "methodCall", ",", "String", "methodNamePattern", ",", "Integer", "numArguments", ")", "{", "Expression", "method", "=", "methodCall", ".", "getMethod", "(", ")", ";", "// !important: perform...
Return true only if the MethodCallExpression represents a method call for the specified method name @param methodCall - the AST MethodCallExpression @param methodNamePattern - the expected name of the method being called @param numArguments - The number of expected arguments @return true only if the method call name matches
[ "Return", "true", "only", "if", "the", "MethodCallExpression", "represents", "a", "method", "call", "for", "the", "specified", "method", "name" ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L425-L440
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isConstructorCall
public static boolean isConstructorCall(Expression expression, List<String> classNames) { return expression instanceof ConstructorCallExpression && classNames.contains(expression.getType().getName()); }
java
public static boolean isConstructorCall(Expression expression, List<String> classNames) { return expression instanceof ConstructorCallExpression && classNames.contains(expression.getType().getName()); }
[ "public", "static", "boolean", "isConstructorCall", "(", "Expression", "expression", ",", "List", "<", "String", ">", "classNames", ")", "{", "return", "expression", "instanceof", "ConstructorCallExpression", "&&", "classNames", ".", "contains", "(", "expression", "...
Return true if the expression is a constructor call on any of the named classes, with any number of parameters. @param expression - the expression @param classNames - the possible List of class names @return as described
[ "Return", "true", "if", "the", "expression", "is", "a", "constructor", "call", "on", "any", "of", "the", "named", "classes", "with", "any", "number", "of", "parameters", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L452-L454
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isConstructorCall
public static boolean isConstructorCall(Expression expression, String classNamePattern) { return expression instanceof ConstructorCallExpression && expression.getType().getName().matches(classNamePattern); }
java
public static boolean isConstructorCall(Expression expression, String classNamePattern) { return expression instanceof ConstructorCallExpression && expression.getType().getName().matches(classNamePattern); }
[ "public", "static", "boolean", "isConstructorCall", "(", "Expression", "expression", ",", "String", "classNamePattern", ")", "{", "return", "expression", "instanceof", "ConstructorCallExpression", "&&", "expression", ".", "getType", "(", ")", ".", "getName", "(", ")...
Return true if the expression is a constructor call on a class that matches the supplied. @param expression - the expression @param classNamePattern - the possible List of class names @return as described
[ "Return", "true", "if", "the", "expression", "is", "a", "constructor", "call", "on", "a", "class", "that", "matches", "the", "supplied", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L462-L464
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.getAnnotation
public static AnnotationNode getAnnotation(AnnotatedNode node, String name) { List<AnnotationNode> annotations = node.getAnnotations(); for (AnnotationNode annot : annotations) { if (annot.getClassNode().getName().equals(name)) { return annot; } } return null; }
java
public static AnnotationNode getAnnotation(AnnotatedNode node, String name) { List<AnnotationNode> annotations = node.getAnnotations(); for (AnnotationNode annot : annotations) { if (annot.getClassNode().getName().equals(name)) { return annot; } } return null; }
[ "public", "static", "AnnotationNode", "getAnnotation", "(", "AnnotatedNode", "node", ",", "String", "name", ")", "{", "List", "<", "AnnotationNode", ">", "annotations", "=", "node", ".", "getAnnotations", "(", ")", ";", "for", "(", "AnnotationNode", "annot", "...
Return the AnnotationNode for the named annotation, or else null. Supports Groovy 1.5 and Groovy 1.6. @param node - the AnnotatedNode @param name - the name of the annotation @return the AnnotationNode or else null
[ "Return", "the", "AnnotationNode", "for", "the", "named", "annotation", "or", "else", "null", ".", "Supports", "Groovy", "1", ".", "5", "and", "Groovy", "1", ".", "6", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L473-L481
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.hasAnnotation
public static boolean hasAnnotation(AnnotatedNode node, String name) { return AstUtil.getAnnotation(node, name) != null; }
java
public static boolean hasAnnotation(AnnotatedNode node, String name) { return AstUtil.getAnnotation(node, name) != null; }
[ "public", "static", "boolean", "hasAnnotation", "(", "AnnotatedNode", "node", ",", "String", "name", ")", "{", "return", "AstUtil", ".", "getAnnotation", "(", "node", ",", "name", ")", "!=", "null", ";", "}" ]
Return true only if the node has the named annotation @param node - the AST Node to check @param name - the name of the annotation @return true only if the node has the named annotation
[ "Return", "true", "only", "if", "the", "node", "has", "the", "named", "annotation" ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L489-L491
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.hasAnyAnnotation
public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) { for (String name : names) { if (hasAnnotation(node, name)) { return true; } } return false; }
java
public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) { for (String name : names) { if (hasAnnotation(node, name)) { return true; } } return false; }
[ "public", "static", "boolean", "hasAnyAnnotation", "(", "AnnotatedNode", "node", ",", "String", "...", "names", ")", "{", "for", "(", "String", "name", ":", "names", ")", "{", "if", "(", "hasAnnotation", "(", "node", ",", "name", ")", ")", "{", "return",...
Return true only if the node has any of the named annotations @param node - the AST Node to check @param names - the names of the annotations @return true only if the node has any of the named annotations
[ "Return", "true", "only", "if", "the", "node", "has", "any", "of", "the", "named", "annotations" ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L499-L506
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.getVariableExpressions
public static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) { Expression leftExpression = declarationExpression.getLeftExpression(); // !important: performance enhancement if (leftExpression instanceof ArrayExpression) { List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions(); return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions; } else if (leftExpression instanceof ListExpression) { List<Expression> expressions = ((ListExpression) leftExpression).getExpressions(); return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions; } else if (leftExpression instanceof TupleExpression) { List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions(); return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions; } else if (leftExpression instanceof VariableExpression) { return Arrays.asList(leftExpression); } // todo: write warning return Collections.emptyList(); }
java
public static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) { Expression leftExpression = declarationExpression.getLeftExpression(); // !important: performance enhancement if (leftExpression instanceof ArrayExpression) { List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions(); return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions; } else if (leftExpression instanceof ListExpression) { List<Expression> expressions = ((ListExpression) leftExpression).getExpressions(); return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions; } else if (leftExpression instanceof TupleExpression) { List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions(); return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions; } else if (leftExpression instanceof VariableExpression) { return Arrays.asList(leftExpression); } // todo: write warning return Collections.emptyList(); }
[ "public", "static", "List", "<", "Expression", ">", "getVariableExpressions", "(", "DeclarationExpression", "declarationExpression", ")", "{", "Expression", "leftExpression", "=", "declarationExpression", ".", "getLeftExpression", "(", ")", ";", "// !important: performance ...
Return the List of VariableExpression objects referenced by the specified DeclarationExpression. @param declarationExpression - the DeclarationExpression @return the List of VariableExpression objects
[ "Return", "the", "List", "of", "VariableExpression", "objects", "referenced", "by", "the", "specified", "DeclarationExpression", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L513-L531
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isFinalVariable
public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) { if (isFromGeneratedSourceCode(declarationExpression)) { return false; } List<Expression> variableExpressions = getVariableExpressions(declarationExpression); if (!variableExpressions.isEmpty()) { Expression variableExpression = variableExpressions.get(0); int startOfDeclaration = declarationExpression.getColumnNumber(); int startOfVariableName = variableExpression.getColumnNumber(); int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode); String sourceLine = sourceCode.getLines().get(sourceLineNumber-1); String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ? sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : ""; return modifiers.contains("final"); } return false; }
java
public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) { if (isFromGeneratedSourceCode(declarationExpression)) { return false; } List<Expression> variableExpressions = getVariableExpressions(declarationExpression); if (!variableExpressions.isEmpty()) { Expression variableExpression = variableExpressions.get(0); int startOfDeclaration = declarationExpression.getColumnNumber(); int startOfVariableName = variableExpression.getColumnNumber(); int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode); String sourceLine = sourceCode.getLines().get(sourceLineNumber-1); String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ? sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : ""; return modifiers.contains("final"); } return false; }
[ "public", "static", "boolean", "isFinalVariable", "(", "DeclarationExpression", "declarationExpression", ",", "SourceCode", "sourceCode", ")", "{", "if", "(", "isFromGeneratedSourceCode", "(", "declarationExpression", ")", ")", "{", "return", "false", ";", "}", "List"...
Return true if the DeclarationExpression represents a 'final' variable declaration. NOTE: THIS IS A WORKAROUND. There does not seem to be an easy way to determine whether the 'final' modifier has been specified for a variable declaration. Return true if the 'final' is present before the variable name.
[ "Return", "true", "if", "the", "DeclarationExpression", "represents", "a", "final", "variable", "declaration", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L541-L558
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isTrue
public static boolean isTrue(Expression expression) { if (expression == null) { return false; } if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) { if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression && "TRUE".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) { return true; } } return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isTrueExpression()) || "Boolean.TRUE".equals(expression.getText()); }
java
public static boolean isTrue(Expression expression) { if (expression == null) { return false; } if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) { if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression && "TRUE".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) { return true; } } return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isTrueExpression()) || "Boolean.TRUE".equals(expression.getText()); }
[ "public", "static", "boolean", "isTrue", "(", "Expression", "expression", ")", "{", "if", "(", "expression", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "expression", "instanceof", "PropertyExpression", "&&", "classNodeImplementsType", "(", ...
Tells you if the expression is true, which can be true or Boolean.TRUE. @param expression expression @return as described
[ "Tells", "you", "if", "the", "expression", "is", "true", "which", "can", "be", "true", "or", "Boolean", ".", "TRUE", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L574-L587
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isFalse
public static boolean isFalse(Expression expression) { if (expression == null) { return false; } if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) { if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression && "FALSE".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) { return true; } } return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isFalseExpression()) || "Boolean.FALSE".equals(expression.getText()); }
java
public static boolean isFalse(Expression expression) { if (expression == null) { return false; } if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) { if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression && "FALSE".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) { return true; } } return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isFalseExpression()) || "Boolean.FALSE".equals(expression.getText()); }
[ "public", "static", "boolean", "isFalse", "(", "Expression", "expression", ")", "{", "if", "(", "expression", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "expression", "instanceof", "PropertyExpression", "&&", "classNodeImplementsType", "(", ...
Tells you if the expression is the false expression, either literal or constant. @param expression expression @return as described
[ "Tells", "you", "if", "the", "expression", "is", "the", "false", "expression", "either", "literal", "or", "constant", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L618-L630
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.respondsTo
public static boolean respondsTo(Object object, String methodName) { MetaClass metaClass = DefaultGroovyMethods.getMetaClass(object); if (!metaClass.respondsTo(object, methodName).isEmpty()) { return true; } Map properties = DefaultGroovyMethods.getProperties(object); return properties.containsKey(methodName); }
java
public static boolean respondsTo(Object object, String methodName) { MetaClass metaClass = DefaultGroovyMethods.getMetaClass(object); if (!metaClass.respondsTo(object, methodName).isEmpty()) { return true; } Map properties = DefaultGroovyMethods.getProperties(object); return properties.containsKey(methodName); }
[ "public", "static", "boolean", "respondsTo", "(", "Object", "object", ",", "String", "methodName", ")", "{", "MetaClass", "metaClass", "=", "DefaultGroovyMethods", ".", "getMetaClass", "(", "object", ")", ";", "if", "(", "!", "metaClass", ".", "respondsTo", "(...
Return true only if the specified object responds to the named method @param object - the object to check @param methodName - the name of the method @return true if the object responds to the named method
[ "Return", "true", "only", "if", "the", "specified", "object", "responds", "to", "the", "named", "method" ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L638-L645
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.classNodeImplementsType
public static boolean classNodeImplementsType(ClassNode node, Class target) { ClassNode targetNode = ClassHelper.make(target); if (node.implementsInterface(targetNode)) { return true; } if (node.isDerivedFrom(targetNode)) { return true; } if (node.getName().equals(target.getName())) { return true; } if (node.getName().equals(target.getSimpleName())) { return true; } if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getName())) { return true; } if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getSimpleName())) { return true; } if (node.getInterfaces() != null) { for (ClassNode declaredInterface : node.getInterfaces()) { if (classNodeImplementsType(declaredInterface, target)) { return true; } } } return false; }
java
public static boolean classNodeImplementsType(ClassNode node, Class target) { ClassNode targetNode = ClassHelper.make(target); if (node.implementsInterface(targetNode)) { return true; } if (node.isDerivedFrom(targetNode)) { return true; } if (node.getName().equals(target.getName())) { return true; } if (node.getName().equals(target.getSimpleName())) { return true; } if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getName())) { return true; } if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getSimpleName())) { return true; } if (node.getInterfaces() != null) { for (ClassNode declaredInterface : node.getInterfaces()) { if (classNodeImplementsType(declaredInterface, target)) { return true; } } } return false; }
[ "public", "static", "boolean", "classNodeImplementsType", "(", "ClassNode", "node", ",", "Class", "target", ")", "{", "ClassNode", "targetNode", "=", "ClassHelper", ".", "make", "(", "target", ")", ";", "if", "(", "node", ".", "implementsInterface", "(", "targ...
This method tells you if a ClassNode implements or extends a certain class. @param node the node @param target the class @return true if the class node 'is a' target
[ "This", "method", "tells", "you", "if", "a", "ClassNode", "implements", "or", "extends", "a", "certain", "class", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L656-L684
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isClosureDeclaration
public static boolean isClosureDeclaration(ASTNode expression) { if (expression instanceof DeclarationExpression) { if (((DeclarationExpression) expression).getRightExpression() instanceof ClosureExpression) { return true; } } if (expression instanceof FieldNode) { ClassNode type = ((FieldNode) expression).getType(); if (AstUtil.classNodeImplementsType(type, Closure.class)) { return true; } else if (((FieldNode) expression).getInitialValueExpression() instanceof ClosureExpression) { return true; } } return false; }
java
public static boolean isClosureDeclaration(ASTNode expression) { if (expression instanceof DeclarationExpression) { if (((DeclarationExpression) expression).getRightExpression() instanceof ClosureExpression) { return true; } } if (expression instanceof FieldNode) { ClassNode type = ((FieldNode) expression).getType(); if (AstUtil.classNodeImplementsType(type, Closure.class)) { return true; } else if (((FieldNode) expression).getInitialValueExpression() instanceof ClosureExpression) { return true; } } return false; }
[ "public", "static", "boolean", "isClosureDeclaration", "(", "ASTNode", "expression", ")", "{", "if", "(", "expression", "instanceof", "DeclarationExpression", ")", "{", "if", "(", "(", "(", "DeclarationExpression", ")", "expression", ")", ".", "getRightExpression", ...
Returns true if the ASTNode is a declaration of a closure, either as a declaration or a field. @param expression the target expression @return as described
[ "Returns", "true", "if", "the", "ASTNode", "is", "a", "declaration", "of", "a", "closure", "either", "as", "a", "declaration", "or", "a", "field", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L694-L709
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.getParameterNames
public static List<String> getParameterNames(MethodNode node) { ArrayList<String> result = new ArrayList<String>(); if (node.getParameters() != null) { for (Parameter parameter : node.getParameters()) { result.add(parameter.getName()); } } return result; }
java
public static List<String> getParameterNames(MethodNode node) { ArrayList<String> result = new ArrayList<String>(); if (node.getParameters() != null) { for (Parameter parameter : node.getParameters()) { result.add(parameter.getName()); } } return result; }
[ "public", "static", "List", "<", "String", ">", "getParameterNames", "(", "MethodNode", "node", ")", "{", "ArrayList", "<", "String", ">", "result", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "if", "(", "node", ".", "getParameters", "(",...
Gets the parameter names of a method node. @param node the node to search parameter names on @return argument names, never null
[ "Gets", "the", "parameter", "names", "of", "a", "method", "node", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L718-L727
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.getArgumentNames
public static List<String> getArgumentNames(MethodCallExpression methodCall) { ArrayList<String> result = new ArrayList<String>(); Expression arguments = methodCall.getArguments(); List<Expression> argExpressions = null; if (arguments instanceof ArrayExpression) { argExpressions = ((ArrayExpression) arguments).getExpressions(); } else if (arguments instanceof ListExpression) { argExpressions = ((ListExpression) arguments).getExpressions(); } else if (arguments instanceof TupleExpression) { argExpressions = ((TupleExpression) arguments).getExpressions(); } else { LOG.warn("getArgumentNames arguments is not an expected type"); } if (argExpressions != null) { for (Expression exp : argExpressions) { if (exp instanceof VariableExpression) { result.add(((VariableExpression) exp).getName()); } } } return result; }
java
public static List<String> getArgumentNames(MethodCallExpression methodCall) { ArrayList<String> result = new ArrayList<String>(); Expression arguments = methodCall.getArguments(); List<Expression> argExpressions = null; if (arguments instanceof ArrayExpression) { argExpressions = ((ArrayExpression) arguments).getExpressions(); } else if (arguments instanceof ListExpression) { argExpressions = ((ListExpression) arguments).getExpressions(); } else if (arguments instanceof TupleExpression) { argExpressions = ((TupleExpression) arguments).getExpressions(); } else { LOG.warn("getArgumentNames arguments is not an expected type"); } if (argExpressions != null) { for (Expression exp : argExpressions) { if (exp instanceof VariableExpression) { result.add(((VariableExpression) exp).getName()); } } } return result; }
[ "public", "static", "List", "<", "String", ">", "getArgumentNames", "(", "MethodCallExpression", "methodCall", ")", "{", "ArrayList", "<", "String", ">", "result", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "Expression", "arguments", "=", "m...
Gets the argument names of a method call. If the arguments are not VariableExpressions then a null will be returned. @param methodCall the method call to search @return a list of strings, never null, but some elements may be null
[ "Gets", "the", "argument", "names", "of", "a", "method", "call", ".", "If", "the", "arguments", "are", "not", "VariableExpressions", "then", "a", "null", "will", "be", "returned", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L737-L760
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isSafe
public static boolean isSafe(Expression expression) { if (expression instanceof MethodCallExpression) { return ((MethodCallExpression) expression).isSafe(); } if (expression instanceof PropertyExpression) { return ((PropertyExpression) expression).isSafe(); } return false; }
java
public static boolean isSafe(Expression expression) { if (expression instanceof MethodCallExpression) { return ((MethodCallExpression) expression).isSafe(); } if (expression instanceof PropertyExpression) { return ((PropertyExpression) expression).isSafe(); } return false; }
[ "public", "static", "boolean", "isSafe", "(", "Expression", "expression", ")", "{", "if", "(", "expression", "instanceof", "MethodCallExpression", ")", "{", "return", "(", "(", "MethodCallExpression", ")", "expression", ")", ".", "isSafe", "(", ")", ";", "}", ...
Tells you if the expression is a null safe dereference. @param expression expression @return true if is null safe dereference.
[ "Tells", "you", "if", "the", "expression", "is", "a", "null", "safe", "dereference", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L802-L810
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isSpreadSafe
public static boolean isSpreadSafe(Expression expression) { if (expression instanceof MethodCallExpression) { return ((MethodCallExpression) expression).isSpreadSafe(); } if (expression instanceof PropertyExpression) { return ((PropertyExpression) expression).isSpreadSafe(); } return false; }
java
public static boolean isSpreadSafe(Expression expression) { if (expression instanceof MethodCallExpression) { return ((MethodCallExpression) expression).isSpreadSafe(); } if (expression instanceof PropertyExpression) { return ((PropertyExpression) expression).isSpreadSafe(); } return false; }
[ "public", "static", "boolean", "isSpreadSafe", "(", "Expression", "expression", ")", "{", "if", "(", "expression", "instanceof", "MethodCallExpression", ")", "{", "return", "(", "(", "MethodCallExpression", ")", "expression", ")", ".", "isSpreadSafe", "(", ")", ...
Tells you if the expression is a spread operator call @param expression expression @return true if is spread expression
[ "Tells", "you", "if", "the", "expression", "is", "a", "spread", "operator", "call" ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L819-L827
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isMethodNode
public static boolean isMethodNode(ASTNode node, String methodNamePattern, Integer numArguments, Class returnType) { if (!(node instanceof MethodNode)) { return false; } if (!(((MethodNode) node).getName().matches(methodNamePattern))) { return false; } if (numArguments != null && ((MethodNode)node).getParameters() != null && ((MethodNode)node).getParameters().length != numArguments) { return false; } if (returnType != null && !AstUtil.classNodeImplementsType(((MethodNode) node).getReturnType(), returnType)) { return false; } return true; }
java
public static boolean isMethodNode(ASTNode node, String methodNamePattern, Integer numArguments, Class returnType) { if (!(node instanceof MethodNode)) { return false; } if (!(((MethodNode) node).getName().matches(methodNamePattern))) { return false; } if (numArguments != null && ((MethodNode)node).getParameters() != null && ((MethodNode)node).getParameters().length != numArguments) { return false; } if (returnType != null && !AstUtil.classNodeImplementsType(((MethodNode) node).getReturnType(), returnType)) { return false; } return true; }
[ "public", "static", "boolean", "isMethodNode", "(", "ASTNode", "node", ",", "String", "methodNamePattern", ",", "Integer", "numArguments", ",", "Class", "returnType", ")", "{", "if", "(", "!", "(", "node", "instanceof", "MethodNode", ")", ")", "{", "return", ...
Tells you if the ASTNode is a method node for the given name, arity, and return type. @param node the node to inspect @param methodNamePattern the expected name of the method @param numArguments the expected number of arguments, optional @param returnType the expected return type, optional @return true if this node is a MethodNode meeting the parameters. false otherwise
[ "Tells", "you", "if", "the", "ASTNode", "is", "a", "method", "node", "for", "the", "given", "name", "arity", "and", "return", "type", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L842-L856
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isVariable
public static boolean isVariable(ASTNode expression, String pattern) { return (expression instanceof VariableExpression && ((VariableExpression) expression).getName().matches(pattern)); }
java
public static boolean isVariable(ASTNode expression, String pattern) { return (expression instanceof VariableExpression && ((VariableExpression) expression).getName().matches(pattern)); }
[ "public", "static", "boolean", "isVariable", "(", "ASTNode", "expression", ",", "String", "pattern", ")", "{", "return", "(", "expression", "instanceof", "VariableExpression", "&&", "(", "(", "VariableExpression", ")", "expression", ")", ".", "getName", "(", ")"...
Tells you if the given ASTNode is a VariableExpression with the given name. @param expression any AST Node @param pattern a string pattern to match @return true if the node is a variable with the specified name
[ "Tells", "you", "if", "the", "given", "ASTNode", "is", "a", "VariableExpression", "with", "the", "given", "name", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L874-L876
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.getClassForClassNode
private static Class getClassForClassNode(ClassNode type) { // todo hamlet - move to a different "InferenceUtil" object Class primitiveType = getPrimitiveType(type); if (primitiveType != null) { return primitiveType; } else if (classNodeImplementsType(type, String.class)) { return String.class; } else if (classNodeImplementsType(type, ReentrantLock.class)) { return ReentrantLock.class; } else if (type.getName() != null && type.getName().endsWith("[]")) { return Object[].class; // better type inference could be done, but oh well } return null; }
java
private static Class getClassForClassNode(ClassNode type) { // todo hamlet - move to a different "InferenceUtil" object Class primitiveType = getPrimitiveType(type); if (primitiveType != null) { return primitiveType; } else if (classNodeImplementsType(type, String.class)) { return String.class; } else if (classNodeImplementsType(type, ReentrantLock.class)) { return ReentrantLock.class; } else if (type.getName() != null && type.getName().endsWith("[]")) { return Object[].class; // better type inference could be done, but oh well } return null; }
[ "private", "static", "Class", "getClassForClassNode", "(", "ClassNode", "type", ")", "{", "// todo hamlet - move to a different \"InferenceUtil\" object\r", "Class", "primitiveType", "=", "getPrimitiveType", "(", "type", ")", ";", "if", "(", "primitiveType", "!=", "null",...
This is private. It is a helper function for the utils.
[ "This", "is", "private", ".", "It", "is", "a", "helper", "function", "for", "the", "utils", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L1009-L1022
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.findFirstNonAnnotationLine
public static int findFirstNonAnnotationLine(ASTNode node, SourceCode sourceCode) { if (node instanceof AnnotatedNode && !((AnnotatedNode) node).getAnnotations().isEmpty()) { // HACK: Groovy line numbers are broken when annotations have a parameter :( // so we must look at the lineNumber, not the lastLineNumber AnnotationNode lastAnnotation = null; for (AnnotationNode annotation : ((AnnotatedNode) node).getAnnotations()) { if (lastAnnotation == null) lastAnnotation = annotation; else if (lastAnnotation.getLineNumber() < annotation.getLineNumber()) lastAnnotation = annotation; } String rawLine = getRawLine(sourceCode, lastAnnotation.getLastLineNumber()-1); if(rawLine == null) { return node.getLineNumber(); } // is the annotation the last thing on the line? if (rawLine.length() > lastAnnotation.getLastColumnNumber()) { // no it is not return lastAnnotation.getLastLineNumber(); } // yes it is the last thing, return the next thing return lastAnnotation.getLastLineNumber() + 1; } return node.getLineNumber(); }
java
public static int findFirstNonAnnotationLine(ASTNode node, SourceCode sourceCode) { if (node instanceof AnnotatedNode && !((AnnotatedNode) node).getAnnotations().isEmpty()) { // HACK: Groovy line numbers are broken when annotations have a parameter :( // so we must look at the lineNumber, not the lastLineNumber AnnotationNode lastAnnotation = null; for (AnnotationNode annotation : ((AnnotatedNode) node).getAnnotations()) { if (lastAnnotation == null) lastAnnotation = annotation; else if (lastAnnotation.getLineNumber() < annotation.getLineNumber()) lastAnnotation = annotation; } String rawLine = getRawLine(sourceCode, lastAnnotation.getLastLineNumber()-1); if(rawLine == null) { return node.getLineNumber(); } // is the annotation the last thing on the line? if (rawLine.length() > lastAnnotation.getLastColumnNumber()) { // no it is not return lastAnnotation.getLastLineNumber(); } // yes it is the last thing, return the next thing return lastAnnotation.getLastLineNumber() + 1; } return node.getLineNumber(); }
[ "public", "static", "int", "findFirstNonAnnotationLine", "(", "ASTNode", "node", ",", "SourceCode", "sourceCode", ")", "{", "if", "(", "node", "instanceof", "AnnotatedNode", "&&", "!", "(", "(", "AnnotatedNode", ")", "node", ")", ".", "getAnnotations", "(", ")...
gets the first non annotation line number of a node, taking into account annotations.
[ "gets", "the", "first", "non", "annotation", "line", "number", "of", "a", "node", "taking", "into", "account", "annotations", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L1076-L1102
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/rule/AbstractAstVisitor.java
AbstractAstVisitor.isFirstVisit
protected boolean isFirstVisit(Object expression) { if (visited.contains(expression)) { return false; } visited.add(expression); return true; }
java
protected boolean isFirstVisit(Object expression) { if (visited.contains(expression)) { return false; } visited.add(expression); return true; }
[ "protected", "boolean", "isFirstVisit", "(", "Object", "expression", ")", "{", "if", "(", "visited", ".", "contains", "(", "expression", ")", ")", "{", "return", "false", ";", "}", "visited", ".", "add", "(", "expression", ")", ";", "return", "true", ";"...
Return true if the AST expression has not already been visited. If it is the first visit, register the expression so that the next visit will return false. @param expression - the AST expression to check @return true if the AST expression has NOT already been visited
[ "Return", "true", "if", "the", "AST", "expression", "has", "not", "already", "been", "visited", ".", "If", "it", "is", "the", "first", "visit", "register", "the", "expression", "so", "that", "the", "next", "visit", "will", "return", "false", "." ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/rule/AbstractAstVisitor.java#L49-L55
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/rule/AbstractAstVisitor.java
AbstractAstVisitor.sourceLineTrimmed
protected String sourceLineTrimmed(ASTNode node) { return sourceCode.line(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1); }
java
protected String sourceLineTrimmed(ASTNode node) { return sourceCode.line(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1); }
[ "protected", "String", "sourceLineTrimmed", "(", "ASTNode", "node", ")", "{", "return", "sourceCode", ".", "line", "(", "AstUtil", ".", "findFirstNonAnnotationLine", "(", "node", ",", "sourceCode", ")", "-", "1", ")", ";", "}" ]
Return the trimmed source line corresponding to the specified AST node @param node - the Groovy AST node
[ "Return", "the", "trimmed", "source", "line", "corresponding", "to", "the", "specified", "AST", "node" ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/rule/AbstractAstVisitor.java#L62-L64
train
CodeNarc/CodeNarc
src/main/java/org/codenarc/rule/AbstractAstVisitor.java
AbstractAstVisitor.sourceLine
protected String sourceLine(ASTNode node) { return sourceCode.getLines().get(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1); }
java
protected String sourceLine(ASTNode node) { return sourceCode.getLines().get(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1); }
[ "protected", "String", "sourceLine", "(", "ASTNode", "node", ")", "{", "return", "sourceCode", ".", "getLines", "(", ")", ".", "get", "(", "AstUtil", ".", "findFirstNonAnnotationLine", "(", "node", ",", "sourceCode", ")", "-", "1", ")", ";", "}" ]
Return the raw source line corresponding to the specified AST node @param node - the Groovy AST node
[ "Return", "the", "raw", "source", "line", "corresponding", "to", "the", "specified", "AST", "node" ]
9a7cec02cb8cbaf845030f2434309e8968f5d7a7
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/rule/AbstractAstVisitor.java#L71-L73
train
seratch/jslack
src/main/java/com/github/seratch/jslack/common/http/SlackHttpClient.java
SlackHttpClient.buildJsonResponse
@Deprecated public static <T> T buildJsonResponse(Response response, Class<T> clazz) throws IOException, SlackApiException { if (response.code() == 200) { String body = response.body().string(); DETAILED_LOGGER.accept(new HttpResponseListener.State(SlackConfig.DEFAULT, response, body)); return GsonFactory.createSnakeCase().fromJson(body, clazz); } else { String body = response.body().string(); throw new SlackApiException(response, body); } }
java
@Deprecated public static <T> T buildJsonResponse(Response response, Class<T> clazz) throws IOException, SlackApiException { if (response.code() == 200) { String body = response.body().string(); DETAILED_LOGGER.accept(new HttpResponseListener.State(SlackConfig.DEFAULT, response, body)); return GsonFactory.createSnakeCase().fromJson(body, clazz); } else { String body = response.body().string(); throw new SlackApiException(response, body); } }
[ "@", "Deprecated", "public", "static", "<", "T", ">", "T", "buildJsonResponse", "(", "Response", "response", ",", "Class", "<", "T", ">", "clazz", ")", "throws", "IOException", ",", "SlackApiException", "{", "if", "(", "response", ".", "code", "(", ")", ...
use parseJsonResponse instead
[ "use", "parseJsonResponse", "instead" ]
4a09680f13c97b33f59bc9b8271fef488c8e1c3a
https://github.com/seratch/jslack/blob/4a09680f13c97b33f59bc9b8271fef488c8e1c3a/src/main/java/com/github/seratch/jslack/common/http/SlackHttpClient.java#L91-L101
train
seratch/jslack
src/main/java/com/github/seratch/jslack/Slack.java
Slack.send
public WebhookResponse send(String url, Payload payload) throws IOException { SlackHttpClient httpClient = getHttpClient(); Response httpResponse = httpClient.postJsonPostRequest(url, payload); String body = httpResponse.body().string(); httpClient.runHttpResponseListeners(httpResponse, body); return WebhookResponse.builder() .code(httpResponse.code()) .message(httpResponse.message()) .body(body) .build(); }
java
public WebhookResponse send(String url, Payload payload) throws IOException { SlackHttpClient httpClient = getHttpClient(); Response httpResponse = httpClient.postJsonPostRequest(url, payload); String body = httpResponse.body().string(); httpClient.runHttpResponseListeners(httpResponse, body); return WebhookResponse.builder() .code(httpResponse.code()) .message(httpResponse.message()) .body(body) .build(); }
[ "public", "WebhookResponse", "send", "(", "String", "url", ",", "Payload", "payload", ")", "throws", "IOException", "{", "SlackHttpClient", "httpClient", "=", "getHttpClient", "(", ")", ";", "Response", "httpResponse", "=", "httpClient", ".", "postJsonPostRequest", ...
Send a data to Incoming Webhook endpoint.
[ "Send", "a", "data", "to", "Incoming", "Webhook", "endpoint", "." ]
4a09680f13c97b33f59bc9b8271fef488c8e1c3a
https://github.com/seratch/jslack/blob/4a09680f13c97b33f59bc9b8271fef488c8e1c3a/src/main/java/com/github/seratch/jslack/Slack.java#L72-L83
train
seratch/jslack
src/main/java/com/github/seratch/jslack/api/rtm/RTMClient.java
RTMClient.updateSession
private void updateSession(Session newSession) { if (this.currentSession == null) { this.currentSession = newSession; } else { synchronized (this.currentSession) { this.currentSession = newSession; } } }
java
private void updateSession(Session newSession) { if (this.currentSession == null) { this.currentSession = newSession; } else { synchronized (this.currentSession) { this.currentSession = newSession; } } }
[ "private", "void", "updateSession", "(", "Session", "newSession", ")", "{", "if", "(", "this", ".", "currentSession", "==", "null", ")", "{", "this", ".", "currentSession", "=", "newSession", ";", "}", "else", "{", "synchronized", "(", "this", ".", "curren...
Overwrites the underlying WebSocket session. @param newSession new session
[ "Overwrites", "the", "underlying", "WebSocket", "session", "." ]
4a09680f13c97b33f59bc9b8271fef488c8e1c3a
https://github.com/seratch/jslack/blob/4a09680f13c97b33f59bc9b8271fef488c8e1c3a/src/main/java/com/github/seratch/jslack/api/rtm/RTMClient.java#L198-L206
train