{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== '免费Z-image图片生成' && linkText !== '免费Z-image图片生成' ) { link.textContent = '免费Z-image图片生成'; link.href = 'https://zimage.run'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Vibevoice' ) { link.textContent = 'Vibevoice'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 替换Pricing链接 - 仅替换一次 else if ( (linkHref.includes('/pricing') || linkHref === '/pricing' || linkText === 'Pricing' || linkText.match(/^s*Pricings*$/i)) && linkText !== '免费去水印' ) { link.textContent = '免费去水印'; link.href = 'https://sora2watermarkremover.net/'; replacedLinks.add(link); } // 替换Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) && linkText !== 'GitHub加速' ) { link.textContent = 'GitHub加速'; link.href = 'https://githubproxy.cc'; replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, '免费Z-image图片生成'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \");\n sb.append(\"\");\n return sb.toString();\n }\n private void getSelectResourceTypeScreen(StringBuffer sb) {\n sb.append(\"

Create new page (step 0)

\");\n sb.append(\"

Select template (resp. resource type)

\");\n sb.append(\"
\");\n ResourceTypeRegistry rtr = new ResourceTypeRegistry();\n ResourceTypeDefinition[] rtds = getResourceTypeDefinitions();\n if (rtds != null) {\n sb.append(\"Template (resp. resource type): \");\n } else {\n sb.append(\"

No resource types!

\");\n }\n sb.append(\"
\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"
\");\n }\n private void getNoSuchScreen(StringBuffer sb) {\n sb.append(\"

No such screen!

\");\n }\n /**\n * Save screen\n */\n private void getSaveScreen(StringBuffer sb) {\n sb.append(\"

Create new page (step 2)

\");\n Path pathOfNewResource = null;\n try {\n pathOfNewResource = create();\n } catch(Exception e) {\n log.warn(e.getMessage(), e);\n sb.append(\"

Exception: \"+e.getMessage()+\"

\");\n sb.append(\"back\");\n return;\n }\n sb.append(\"

Resource has been created

\");\n HttpServletRequest request = getRequest();\n Enumeration parameters = request.getParameterNames();\n if (parameters.hasMoreElements()) {\n sb.append(\"
    \");\n while (parameters.hasMoreElements()) {\n String parameter = (String) parameters.nextElement();\n if (parameter.indexOf(\"rp.\") == 0) {\n sb.append(\"
  • \"+parameter+\": \"+request.getParameter(parameter)+\"
  • \");\n }\n }\n sb.append(\"
\");\n }\n if (log.isDebugEnabled()) log.debug(\"New Resource: \" + PathUtil.backToRealm(getPath()) + \", \" + pathOfNewResource);\n // NOTE: Back to realm has the form of ./ or ../ or ../../ etc., hence drop the leading slash!\n if (pathOfNewResource != null) {\n String href = PathUtil.backToRealm(getPath()) + pathOfNewResource.toString().substring(1);\n sb.append(\"

New resource can be accessed at: \" + href + \"

\");\n } else {\n sb.append(\"

Please note that no path/URL has been associated with the newly created resource, because it might be some internally used resource.

\");\n }\n }\n private void getResourceScreen(StringBuffer sb) {\n String rtps = getRequest().getParameter(\"resource-type\");\n String resNamespace = rtps.substring(0, rtps.indexOf(\"::\"));\n String resName = rtps.substring(rtps.indexOf(\"::\") + 2);\n ResourceTypeRegistry rtr = new ResourceTypeRegistry();\n if (getRequest().getParameter(\"create-new-folder\") != null && !getRequest().getParameter(\"create-new-folder\").equals(\"\")) {\n try {\n create(getRequest().getParameter(\"create-new-folder\"), getRequest().getParameter(\"lookin\"), \"http:\n } catch (Exception e) {\n sb.append(\"

Could not create folder. Exception: \" + e + \"

\");\n log.error(e.getMessage(), e);\n }\n }\n try {\n String universalName = \"<{\"+ resNamespace +\"}\"+ resName +\"/>\";\n log.debug(\"Universal Name: \" + universalName);\n Resource resource = rtr.newResource(universalName);\n if (resource != null) {\n if (ResourceAttributeHelper.hasAttributeImplemented(resource, \"Creatable\", \"2\")) {\n sb.append(\"

Create new page (step 1)

\");\n sb.append(\"

Enter/Select template (resp. resource) specific parameters and \\\"Save As\\\"

\");\n sb.append(\"
\");\n sb.append(\"

Template (resp. resource type): \" + resName + \" (\"+resNamespace+\")

\");\n // TODO: Add this parameter to the continuation within the session!\n sb.append(\"\");\n Property[] defaultProperties = getDefaultProperties(resName, resNamespace);\n String[] propertyNames = ((CreatableV2) resource).getPropertyNames();\n if ((propertyNames != null && propertyNames.length > 0) || defaultProperties != null) {\n sb.append(\"

Resource specific properties:

\");\n } else {\n sb.append(\"

No resource specific properties!

\");\n }\n if (propertyNames != null && propertyNames.length > 0) {\n sb.append(\"\");\n for (int i = 0; i < propertyNames.length; i++) {\n sb.append(\"\");\n }\n sb.append(\"
\" + propertyNames[i] + \":&#160;&#160;&#160;\");\n String propertyType = ((CreatableV2) resource).getPropertyType(propertyNames[i]);\n if (propertyType != null && propertyType.equals(CreatableV2.TYPE_UPLOAD)) {\n sb.append(\"
\");\n } else if (propertyType != null && propertyType.equals(CreatableV2.TYPE_SELECT)) {\n Object defaultValues = ((CreatableV2) resource).getProperty(propertyNames[i]);\n if (defaultValues instanceof java.util.HashMap) {\n sb.append(\"
\");\n } else {\n sb.append(\"Exception: Parameter doesn't seem to be a of type SELECT: \" + propertyNames[i]);\n }\n } else if (propertyType != null && propertyType.equals(CreatableV2.TYPE_PASSWORD)) {\n //sb.append(\"
\");\n Object value = ((CreatableV2) resource).getProperty(propertyNames[i]);\n if (value == null) {\n sb.append(\"
\");\n } else {\n sb.append(\"
\");\n }\n } else {\n log.debug(\"Let's assume the property is of type text ...\");\n Object value = ((CreatableV2) resource).getProperty(propertyNames[i]);\n if (value == null) {\n sb.append(\"
\");\n } else {\n sb.append(\"
\");\n }\n }\n sb.append(\"
\");\n }\n if (defaultProperties != null) {\n sb.append(\"
    \");\n for (int i = 0; i < defaultProperties.length; i++) {\n sb.append(\"
  • \");\n sb.append(\"Default property: \" + defaultProperties[i]);\n sb.append(\"\");\n sb.append(\"
  • \");\n }\n sb.append(\"
\");\n }\n sb.append(\"

\");\n sb.append(\"
\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"
Save as:
\");\n sb.append(\"
\");\n sb.append(getLookUp());\n sb.append(\"
\");\n sb.append(\"
\");\n String createName = getRequest().getParameter(\"create-name\");\n if (createName != null) {\n sb.append(\"New name: \");\n } else {\n sb.append(\"New name: \");\n }\n sb.append(\"
\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"
\");\n sb.append(\"
\");\n sb.append(\"
\");\n // TODO: Display realm navigation (sitetree, topic map, ...) resp. introduce another step\n }\n }\n } catch (Exception e) {\n sb.append(\"

Exception: \" + e + \"

\");\n log.error(e.getMessage(), e);\n }\n }\n /**\n * Creates new resource\n * @return Path of new resource\n */\n private Path create() throws Exception {\n return create(getRequest().getParameter(\"create-name\"), getRequest().getParameter(\"lookin\"), getRequest().getParameter(\"resource-type\"));\n }\n /**\n * Creates new resource\n * @param String createName\n * @param String lookinPath\n * @param String resourceType\n * @return Path of new resource\n */\n private Path create(String createName, String lookinPath, String resourceType) throws Exception {\n org.wyona.yanel.core.map.Realm realm = getRealm();\n Path pathOfResourceCreator = new Path(getPath());\n org.wyona.commons.io.Path parent = new org.wyona.commons.io.Path(pathOfResourceCreator.toString()).getParent();\n Path pathOfNewResource = new Path(getParentOfNewResource(parent, lookinPath).toString() + createName);\n if (log.isDebugEnabled()) log.debug(\"Path of new resource: \" + pathOfNewResource);\n pathOfNewResource = new Path(removeTooManySlashes(pathOfNewResource.toString()));\n if (log.isDebugEnabled()) log.debug(\"Path of new resource without too many slashes: \" + pathOfNewResource);\n String rtps = resourceType;\n String resNamespace = rtps.substring(0, rtps.indexOf(\"::\"));\n String resName = rtps.substring(rtps.indexOf(\"::\") + 2);\n Resource newResource = yanel.getResourceManager().getResource(getEnvironment(), realm, pathOfNewResource.toString(), new ResourceConfiguration(resName, resNamespace, null));\n if (newResource != null) {\n if (ResourceAttributeHelper.hasAttributeImplemented(newResource, \"Creatable\", \"2\")) {\n createName = ((CreatableV2) newResource).getCreateName(createName);\n if (createName != null && createName.equals(\"\")) {\n throw new Exception(\"Please enter a name!\");\n }\n if (createName == null) {\n pathOfNewResource = null;\n newResource.setPath(null);\n } else {\n pathOfNewResource = new Path(removeTooManySlashes(getParentOfNewResource(parent, lookinPath).toString()) + createName);\n newResource.setPath(pathOfNewResource.toString());\n }\n ((CreatableV2) newResource).create(request);\n if (pathOfNewResource != null) {\n createResourceConfiguration(newResource);\n }\n } else {\n throw new Exception(\"creation NOT successfull!\");\n }\n } else {\n throw new Exception(\"creation NOT successful (newResource == null)!\");\n }\n return pathOfNewResource;\n }\n /**\n * Create resource configuration (yanel-rc)\n */\n private void createResourceConfiguration(Resource newResource) throws Exception {\n StringBuffer rcContent = new StringBuffer(\"\\n\\n\");\n rcContent.append(\"\\n\\n\");\n java.util.HashMap rtiProperties = ((CreatableV2) newResource).createRTIProperties(request);\n if (rtiProperties != null) {\n if (log.isDebugEnabled()) log.debug(rtiProperties + \" \" + PathUtil.getRTIPath(newResource.getPath()));\n java.util.Iterator iterator = rtiProperties.keySet().iterator();\n while (iterator.hasNext()) {\n String property = (String) iterator.next();\n String value = (String) rtiProperties.get(property);\n if (value != null) {\n rcContent.append(\"\\n\");\n if(log.isDebugEnabled()) log.debug(\"Set Property: \" + property + \", \" + value);\n } else {\n log.warn(\"Property value is null: \" + property);\n }\n }\n } else {\n log.warn(\"No RTI properties: \" + newResource.getPath());\n }\n rcContent.append(\"\");\n org.wyona.yarep.core.Repository rcRepo = newResource.getRealm().getRTIRepository();\n org.wyona.commons.io.Path newRCPath = new org.wyona.commons.io.Path(PathUtil.getRCPath(newResource.getPath()));\n if (log.isDebugEnabled()) log.debug(newRCPath);\n org.wyona.yanel.core.util.YarepUtil.addNodes(rcRepo, newRCPath.toString(), org.wyona.yarep.core.NodeType.RESOURCE);\n java.io.Writer writer = new java.io.OutputStreamWriter(rcRepo.getNode(newRCPath.toString()).getOutputStream());\n writer.write(rcContent.toString());\n writer.close();\n }\n /**\n * Get resource type definitions\n */\n private ResourceTypeDefinition[] getResourceTypeDefinitions() {\n ResourceTypeRegistry rtr = new ResourceTypeRegistry();\n ResourceConfiguration rc = getConfiguration();\n Document customConfigDoc = rc.getCustomConfiguration();\n if (customConfigDoc != null) {\n Configuration config = ConfigurationUtil.toConfiguration(customConfigDoc.getDocumentElement());\n Configuration resourceTypesConfig = config.getChild(\"resource-types\", false);\n if (resourceTypesConfig != null) {\n Configuration[] resourceTypeConfigs = resourceTypesConfig.getChildren(\"resource-type\");\n if (resourceTypeConfigs.length == 0) return null;\n ResourceTypeDefinition[] rtds = new ResourceTypeDefinition[resourceTypeConfigs.length];\n for (int i = 0; i < resourceTypeConfigs.length; i++) {\n try {\n String universalName = \"<{\"+resourceTypeConfigs[i].getAttribute(\"namespace\")+\"}\"+resourceTypeConfigs[i].getAttribute(\"name\")+\"/>\";\n rtds[i] = rtr.getResourceTypeDefinition(universalName);\n log.debug(\"Resource Type: \" + universalName);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return null;\n }\n }\n return rtds;\n }\n }\n ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions();\n return rtds;\n }\n /**\n * Get default properties from custom configuration\n */\n private Property[] getDefaultProperties(String resName, String resNamespace) {\n Document customConfigDoc = getConfiguration().getCustomConfiguration();\n if (customConfigDoc != null) {\n Configuration config = ConfigurationUtil.toConfiguration(customConfigDoc.getDocumentElement());\n Configuration resourceTypesConfig = config.getChild(\"resource-types\", false);\n if (resourceTypesConfig != null) {\n Configuration[] resourceTypeConfigs = resourceTypesConfig.getChildren(\"resource-type\");\n if (resourceTypeConfigs.length == 0) return null;\n for (int i = 0; i < resourceTypeConfigs.length; i++) {\n try {\n if (resourceTypeConfigs[i].getAttribute(\"namespace\").equals(resNamespace) && resourceTypeConfigs[i].getAttribute(\"name\").equals(resName)) {\n log.debug(\"Resource Type Found: \" + resName + \", \" + resNamespace);\n Configuration[] propertyConfigs = resourceTypeConfigs[i].getChildren(\"property\");\n Property[] props = new Property[propertyConfigs.length];\n for (int k = 0; k < propertyConfigs.length; k++) {\n props[k] = new Property(propertyConfigs[k].getAttribute(\"name\"), propertyConfigs[k].getAttribute(\"value\"));\n log.debug(\"Property: \" + props[k]);\n }\n return props;\n }\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return null;\n }\n }\n }\n }\n return null;\n }\n /**\n * Get the display name from custom configuration\n */\n private String getDisplayName(String resName, String resNamespace) {\n Document customConfigDoc = getConfiguration().getCustomConfiguration();\n if (customConfigDoc != null) {\n try {\n org.jdom.Document jdomDocument = new org.jdom.input.DOMBuilder().build(customConfigDoc);\n org.jdom.xpath.XPath xpath = org.jdom.xpath.XPath.newInstance(\"/yanel:custom-config/rc:resource-types/rc:resource-type[@name='\" + resName + \"']/rc:display-name\");\n xpath.addNamespace(\"yanel\", \"http:\n xpath.addNamespace(\"rc\", \"http:\n org.jdom.Element displayNameElement = (org.jdom.Element) xpath.selectSingleNode(jdomDocument);\n if (displayNameElement != null) {\n // TODO: It seems like document does not contain text nodes ...\n if (log.isDebugEnabled()) log.debug(\"Display name: \" + displayNameElement + \" :: \" + displayNameElement.getText() + \" :: \" + displayNameElement.getName());\n return displayNameElement.getText();\n } else {\n log.warn(\"No display name: \" + resName);\n return resName;\n }\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return resName;\n }\n }\n return resName;\n }\n /**\n * Return sitetree\n */\n private StringBuffer getLookUp() {\n StringBuffer sb = new StringBuffer(\"\");\n //Sitetree sitetree = (Sitetree) getYanel().getBeanFactory().getBean(\"repo-navigation\");\n Sitetree sitetree = getRealm().getRepoNavigation();\n Node node = null;\n String lookinPath = getRequest().getParameter(\"lookin\");\n if (lookinPath != null) {\n node = sitetree.getNode(getRealm(), lookinPath);\n } else {\n node = sitetree.getNode(getRealm(), getPath());\n }\n if (node != null) {\n if (node.isCollection()) {\n if(log.isDebugEnabled()) log.debug(\"Is Collection: \" + node.getName());\n } else if (node.isResource()) {\n if (log.isDebugEnabled()) log.debug(\"Is Resource: \" + node.getName());\n node = node.getParent();\n } else {\n log.error(\"Neither collection nor resource: \" + getPath());\n }\n } else {\n log.error(\"No such path '\" + getPath() + \"' within sitetree! Root node will be used.\");\n node = sitetree.getNode(getRealm(), \"/\");\n }\n String rtps = getRequest().getParameter(\"resource-type\");\n String resNamespace = rtps.substring(0, rtps.indexOf(\"::\"));\n String resName = rtps.substring(rtps.indexOf(\"::\") + 2);\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"
Look in: \" + node.getPath() + \"&#160;&#160;&#160;New folder: &#160; \");\n String parent = \"/\";\n if (!node.getPath().equals(\"/\")) {\n parent = new org.wyona.commons.io.Path(node.getPath()).getParent().toString();\n }\n if (log.isDebugEnabled()) log.debug(\"Parent: \" + parent);\n if (ajaxBrowser) {\n sb.append(\"\\\"go\");\n } else {\n sb.append(\"\\\"go\");\n }\n sb.append(\"
\");\n sb.append(\"
\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n sb.append(\"\");\n Node[] children = node.getChildren();\n for (int i = 0; i < children.length; i++) {\n String resourceTypeName;\n try {\n resourceTypeName = yanel.getResourceManager().getResource(getEnvironment(), realm, children[i].getPath()).getResourceTypeLocalName();\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n resourceTypeName = \"?\";\n }\n if (children[i].isCollection()) {\n // TODO: Also append resource specific parameters (AJAX ...)\n if (ajaxBrowser) {\n sb.append(\"\");\n } else {\n sb.append(\"\");\n }\n } else if (children[i].isResource()) {\n sb.append(\"\");\n } else {\n sb.append(\"\");\n }\n }\n sb.append(\"\");\n sb.append(\"
TypeNameResource Type
\\\"Collection:\\\"/\" + children[i].getName() + \"\" + resourceTypeName + \"
\\\"Collection:\\\"/\" + children[i].getName() + \"\" + resourceTypeName + \"
\\\"Resource:\\\"/\"+children[i].getName()+\"\" + resourceTypeName + \"
?\"+children[i].getName()+\"-
\");\n sb.append(\"\");\n sb.append(\"
\");\n sb.append(\"
\");\n return sb;\n }\n /**\n * Get XSLT path\n */\n private String[] getXSLTPath(String path) throws Exception {\n String[] xsltPath = getResourceConfigProperties(\"xslt\");\n if (xsltPath != null && xsltPath.length > 0) return xsltPath;\n log.info(\"No XSLT Path within: \" + path);\n return null;\n }\n /**\n * Remove slashes if there are too many, e.g. /foo//bar.html is being transformed into /foo/bar.html\n */\n private String removeTooManySlashes(String path) {\n StringBuffer sb = new StringBuffer();\n boolean previousCharWasSlash = false;\n for (int i = 0; i < path.length(); i++) {\n char c = path.charAt(i);\n if (c == '/' && previousCharWasSlash) {\n if (log.isDebugEnabled()) log.debug(\"Do not append this slash: \" + i);\n } else {\n sb.append(c);\n }\n if (c == '/') {\n previousCharWasSlash = true;\n } else {\n previousCharWasSlash = false;\n }\n }\n return sb.toString();\n }\n private Path getParentOfNewResource(org.wyona.commons.io.Path parent, String lookinPath) {\n Path parentOfNewResource = null;\n if(parent.equals(\"null\")) {\n // if pathOfResourceCreator is ROOT\n parentOfNewResource = new Path(\"/\" + lookinPath + \"/\");\n } else if(parent.toString().equals(\"/\")){\n parentOfNewResource = new Path(parent + \"/\" + lookinPath + \"/\");\n } else {\n parentOfNewResource = new Path(\"/\" + lookinPath + \"/\");\n }\n return parentOfNewResource;\n }\n private String getReferer() {\n if(request.getParameter(\"referer\") != null) {\n return request.getParameter(\"referer\");\n }\n if(request.getHeader(\"referer\") != null) {\n return replaceEntities(request.getHeader(\"referer\"));\n }\n return PathUtil.backToRealm(getPath());\n }\n /**\n * Replaces some characters by their corresponding xml entities.\n * This method escapes those characters which must not occur in an xml text node.\n * @param string\n * @return escaped string\n */\n public String replaceEntities(String str) {\n // there may be some &amp; and some & mixed in the input, so first transform all\n // &amp; to & and then transform all & back to &amp;\n // this way we don't get double escaped &amp;amp;\n str = str.replaceAll(\"&amp;\", \"&\");\n str = str.replaceAll(\"&\", \"&amp;\");\n str = str.replaceAll(\"<\", \"&lt;\");\n return str;\n }\n}\nclass Property {\n private String name;\n private String value;\n public Property(String name, String value) {\n this.name = name;\n this.value = value;\n }\n public String getName() {\n return name;\n }\n public String getValue() {\n return value;\n }\n public String toString() {\n return name + \" = \" + value;\n }\n}"}}},{"rowIdx":1240,"cells":{"answer":{"kind":"string","value":"package org.wyona.yanel.servlet.toolbar.impl;\nimport javax.servlet.http.HttpServletRequest;\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.LogManager;\nimport org.wyona.security.core.api.Identity;\nimport org.wyona.yanel.core.Resource;\nimport org.wyona.yanel.core.api.attributes.VersionableV2;\nimport org.wyona.yanel.core.map.Map;\nimport org.wyona.yanel.core.util.PathUtil;\nimport org.wyona.yanel.core.util.ResourceAttributeHelper;\nimport org.wyona.yanel.servlet.YanelServlet;\nimport org.wyona.yanel.servlet.menu.Menu;\nimport org.wyona.yanel.servlet.toolbar.YanelToolbar;\nimport org.wyona.yanel.servlet.toolbar.YanelToolbarException;\n/**\n * The from scratch realm toolbar example, wrapping a {@link Menu}.\n */\npublic class FromScratchRealmToolbar implements YanelToolbar {\n private static Logger log = LogManager.getLogger(FromScratchRealmToolbar.class);\n private final Menu menu;\n public FromScratchRealmToolbar() {\n this.menu = new org.wyona.yanel.servlet.menu.impl.DefaultMenuV2();\n }\n /**\n * @see org.wyona.yanel.servlet.toolbar.YanelToolbar#getToolbarBodyStart(Resource, HttpServletRequest, Map, String)\n */\n public String getToolbarBodyStart(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) {\n try {\n String backToRealm = PathUtil.backToRealm(resource.getPath());\n StringBuilder buf = new StringBuilder();\n buf.append(\"
\");\n buf.append(\"
\");\n buf.append(getToolbarMenus(resource, request, map, reservedPrefix));\n buf.append(\"
\");\n buf.append(getInfo(resource, request, map, backToRealm, reservedPrefix));\n buf.append(\"\");\n buf.append(\"\");\n buf.append(\"\");\n buf.append(\"
\");\n buf.append(\"
\");\n return buf.toString();\n } catch (RuntimeException e) {\n throw e;\n } catch (Exception e) {\n throw new YanelToolbarException(\"Couldn't generate toolbar body start markup: \" + e.getMessage(), e);\n }\n }\n /**\n * @see org/wyona/yanel/servlet/toolbar/YanelToolbar#getToolbarHeader(Resource, HttpServletRequest, Map, String)\n */\n public String getToolbarHeader(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) {\n String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath());\n StringBuilder sb = new StringBuilder();\n sb.append(\"\");\n sb.append(System.getProperty(\"line.separator\"));\n sb.append(\"\");\n sb.append(System.getProperty(\"line.separator\"));\n sb.append(\"\");\n sb.append(System.getProperty(\"line.separator\"));\n // If browser is Mozilla (gecko engine rv:1.7)\n if (request.getHeader(\"User-Agent\").indexOf(\"rv:1.7\") >= 0) {\n sb.append(\"\");\n sb.append(System.getProperty(\"line.separator\"));\n }\n // If browser is IE\n if (request.getHeader(\"User-Agent\").indexOf(\"compatible; MSIE\") >= 0\n && request.getHeader(\"User-Agent\").indexOf(\"Windows\") >= 0) {\n sb.append(\"\");\n sb.append(System.getProperty(\"line.separator\"));\n sb.append(\"\");\n }\n // If browser is IE6\n if (request.getHeader(\"User-Agent\").indexOf(\"compatible; MSIE 6\") >= 0\n && request.getHeader(\"User-Agent\").indexOf(\"Windows\") >= 0) {\n sb.append(\"\");\n sb.append(System.getProperty(\"line.separator\"));\n }\n sb.append(\"\");\n return sb.toString();\n }\n /**\n * @see org.wyona.yanel.servlet.toolbar.YanelToolbar#getToolbarBodyEnd(Resource, HttpServletRequest, Map, String)\n */\n public String getToolbarBodyEnd(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) {\n return \"
\";\n }\n /**\n * Gets the toolbar menus.\n */\n private String getToolbarMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws Exception {\n return menu.getAllMenus(resource, request, map, reservedPrefix);\n }\n /**\n * Gets information such as realm name, user name, etc.\n */\n private String getInfo(Resource resource, HttpServletRequest request, Map map, String backToRealm, String reservedPrefix) throws Exception {\n String userLanguage = getUserLanguage(resource);\n StringBuilder buf = new StringBuilder();\n buf.append(\"\");\n //buf.append(\"Version: \" + yanel.getVersion() + \"-r\" + yanel.getRevision() + \"&#160;&#160;\");\n if (ResourceAttributeHelper.hasAttributeImplemented(resource, \"Versionable\", \"2\")) {\n VersionableV2 versionableRes = (VersionableV2) resource;\n if (versionableRes.isCheckedOut()) {\n buf.append(getLabel(\"page\", userLanguage) + \": Locked by \" + versionableRes.getCheckoutUserID()\n + \" (unlock)&#160;&#160;\");\n }\n }\n org.wyona.yarep.core.Node[] nodes = null;\n try {\n nodes = resource.getRealm().getRepository().getSearcher().searchProperty(\"workflow-state\", \"review\", \"/\");\n } catch(org.wyona.yarep.core.search.SearchException e) {\n log.error(e, e); // INFO: Do not throw exception in order to make it more fault tolerant, for example the SearchException is thrown if no index exists\n }\n if (nodes != null && nodes.length > 0) {\n buf.append(\"Workflow: \" + nodes.length + \" pages to be reviewed&#160;&#160;\");\n }\n Identity identity = resource.getEnvironment().getIdentity();\n if (identity != null && !identity.isWorld()) {\n buf.append(getLabel(\"user\", userLanguage) + \": \" + identity.getAlias() + \"\");\n } else {\n buf.append(getLabel(\"user\", userLanguage) + \": Not signed in!\");\n }\n buf.append(\"\");\n return buf.toString();\n }\n /**\n * Gets user language (order: profile, browser, ...) (Also see\n * org/wyona/yanel/servlet/menu/Menu.java)\n */\n private String getUserLanguage(Resource resource) throws Exception {\n Identity identity = resource.getEnvironment().getIdentity();\n String language = resource.getRequestedLanguage();\n String userID = identity.getUsername();\n if (userID != null) {\n String userLanguage = resource.getRealm().getIdentityManager().getUserManager().getUser(userID).getLanguage();\n if (userLanguage != null) {\n language = userLanguage;\n log.debug(\"Use user profile language: \" + language);\n } else {\n log.debug(\"Use requested language: \" + language);\n }\n }\n return language;\n }\n /**\n * Gets i18n (TODO: Replace this by something more generic)\n *\n * @param key I18n key\n * @param language Language\n */\n private static String getLabel(String key, String language) {\n if (language.equals(\"de\")) {\n if (key.equals(\"user\")) {\n return \"Benutzer\";\n } else if (key.equals(\"page\")) {\n return \"Seite\";\n } else {\n log.warn(\"Key '\" + key + \"' not supported yet by requested language '\" + language + \"'. Fallback to english!\");\n return getLabel(key, \"en\");\n }\n } else if (language.equals(\"en\")) {\n if (key.equals(\"user\")) {\n return \"User\";\n } else if (key.equals(\"page\")) {\n return \"Page\";\n } else {\n log.warn(\"Key '\" + key + \"' not supported yet!\");\n return key;\n }\n } else {\n log.warn(\"Language '\" + language + \"' not supported yet. Fallback to english!\");\n return getLabel(key, \"en\");\n }\n }\n}"}}},{"rowIdx":1241,"cells":{"answer":{"kind":"string","value":"package org.jboss.as.test.integration.management.cli;\nimport java.io.IOException;\nimport org.jboss.arquillian.container.test.api.RunAsClient;\nimport org.jboss.arquillian.junit.Arquillian;\nimport org.jboss.as.controller.descriptions.ModelDescriptionConstants;\nimport org.jboss.as.test.integration.management.base.AbstractCliTestBase;\nimport org.jboss.as.test.integration.management.util.CLIOpResult;\nimport org.jboss.dmr.ModelNode;\nimport org.jboss.dmr.ModelType;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n@RunWith(Arquillian.class)\n@RunAsClient\npublic class WildCardReadsTestCase extends AbstractCliTestBase {\n /*\n * This address meets a particular set of requirements needed to validate the WFLY-2527 fix:\n * 1) the distributed-cache=dist resource does not actually exist. Therefore eviction=XXX child resources also do not\n * TBH I'm not certain this aspect is all that critical, but don't blindly remove it.\n * 2) There is no ManagementResourceRegistration for eviction=*\n * 3) There are MRR's for eviction=XXX, eviction=YYY, etc\n * 4) The descriptions for each of those eviction=XXX, eviction=YYY, etc are identical\n *\n * TODO add some assertions that validate that 1-4 still hold true, in order to ensure the test continues\n * to validate the expected behavior\n */\n private static final String OP_PATTERN = \"/subsystem=infinispan/cache-container=web/distributed-cache=dist/eviction=%s:%s\";\n private static final String READ_OP_DESC_OP = ModelDescriptionConstants.READ_OPERATION_DESCRIPTION_OPERATION + \"(name=%s)\";\n private static final String READ_RES_DESC_OP = ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION + \"(access-control=combined-descriptions,operations=true,recursive=true)\";\n private static final String EVICTION = \"EVICTION\";\n @BeforeClass\n public static void before() throws Exception {\n initCLI();\n }\n @AfterClass\n public static void after() throws Exception {\n closeCLI();\n }\n /**\n * Tests WFLY-2527 added behavior of supporting read-operation-description for\n * wildcard addresses where there is no generic resource registration for the type\n */\n @Test\n public void testLenientReadOperationDescription() throws IOException {\n cli.sendLine(String.format(OP_PATTERN, EVICTION, ModelDescriptionConstants.READ_OPERATION_NAMES_OPERATION));\n CLIOpResult opResult = cli.readAllAsOpResult();\n Assert.assertTrue(opResult.isIsOutcomeSuccess());\n for (ModelNode node : opResult.getResponseNode().get(ModelDescriptionConstants.RESULT).asList()) {\n String opPart = String.format(READ_OP_DESC_OP, node.asString());\n cli.sendLine(String.format(OP_PATTERN, EVICTION, opPart));\n opResult = cli.readAllAsOpResult();\n Assert.assertTrue(opResult.isIsOutcomeSuccess());\n ModelNode specific = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT);\n cli.sendLine(String.format(OP_PATTERN, \"*\", opPart));\n opResult = cli.readAllAsOpResult();\n Assert.assertTrue(opResult.isIsOutcomeSuccess());\n Assert.assertEquals(\"mismatch for \" + node.asString(), specific, opResult.getResponseNode().get(ModelDescriptionConstants.RESULT));\n }\n }\n /**\n * Tests WFLY-2527 fix.\n */\n @Test\n public void testReadResourceDescriptionNoGenericRegistration() throws IOException {\n cli.sendLine(String.format(OP_PATTERN, EVICTION, READ_RES_DESC_OP));\n CLIOpResult opResult = cli.readAllAsOpResult();\n Assert.assertTrue(opResult.isIsOutcomeSuccess());\n ModelNode specific = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT);\n cli.sendLine(String.format(OP_PATTERN, \"*\", READ_RES_DESC_OP));\n opResult = cli.readAllAsOpResult();\n Assert.assertTrue(opResult.isIsOutcomeSuccess());\n ModelNode generic = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT);\n Assert.assertEquals(ModelType.LIST, generic.getType());\n Assert.assertEquals(1, generic.asInt());\n Assert.assertEquals(specific, generic.get(0).get(ModelDescriptionConstants.RESULT));\n }\n}"}}},{"rowIdx":1242,"cells":{"answer":{"kind":"string","value":"public class Solution {\n public int[] intersection(int[] nums1, int[] nums2) {\n Set temp = new HashSet<>();\n for (int i = 0; i < nums1.length; i++) {\n temp.add(nums1[i]);\n }\n }\n List numbers = new ArrayList<>();\n for (int i = 0; i < nums2.length; i++) {\n if (temp.contains(nums2[i]))\n {\n numbers.add(nums2[i]);\n temp.remove(nums2[i]);\n }\n }\n // transfer array\n int newArray[] = new int[numbers.size()];\n for (int i = 0; i < numbers.size(); i++) {\n newArray[i] = numbers.get(i);\n }\n return newArray;\n}\n}"}}},{"rowIdx":1243,"cells":{"answer":{"kind":"string","value":"import java.awt.Point;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseWheelEvent;\nimport java.awt.geom.Point2D;\nimport javax.media.opengl.GL;\nimport javax.media.opengl.GLAutoDrawable;\nimport javax.media.opengl.GLCanvas;\nimport javax.vecmath.Matrix4f;\nimport javax.vecmath.Point3d;\nimport javax.vecmath.Quat4f;\nimport javax.vecmath.Vector2f;\nimport javax.vecmath.Vector3f;\n/// Extends the simple renderer with a Trackball controller\npublic class ArcballRenderer extends SimpleRenderer {\n private Matrix4f LastRot = new Matrix4f();\n private ArcBallHelper arcBall = null;\n private Arcball arcball_geo = new Arcball();\n /** Controls zoom speed */\n float scale_move_ratio = .05f; /// TODO make the zoom ratio exposed!\n /** Controls pan speed */\n float pan_move_ratio = 1;\n public ArcballRenderer(GLCanvas canvas) {\n super(canvas);\n LastRot.setIdentity();\n arcBall = new ArcBallHelper(canvas.getWidth(), canvas.getHeight());\n adjust_pan_speed(canvas.getWidth(), canvas.getHeight());\n }\n /** Make sure panning speed is ~constant\n * TODO use it*/\n private void adjust_pan_speed(int width, int height){\n /// Pan speed adjusted normalized w.r.t. window size\n pan_move_ratio = 1.0f / ((float) canvas.getWidth());\n // System.out.printf(\"pan_move_ratio: %f\\n\", pan_move_ratio);\n }\n @Override\n public void display(GLAutoDrawable drawable) {\n GL gl = drawable.getGL();\n gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);\n gl.glMatrixMode(GL.GL_MODELVIEW);\n gl.glLoadIdentity();\n // Make unit sphere fit loosely\n gl.glScaled(.85, .85, .85);\n // Arcball rotates, but doesn't translate/scale\n gl.glMultMatrixf(super.getRotation(), 0);\n arcball_geo.draw(gl);\n // Models are also scaled translated\n gl.glScaled(getScale(), getScale(), getScale());\n gl.glTranslated(getTx(),getTy(),getTz());\n for (int i = 0; i < objects.size(); i++)\n objects.elementAt(i).draw(gl);\n gl.glFlush();\n }\n @Override // Arcball needs to know about window geometry\n public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {\n super.reshape(drawable, x, y, width, height);\n arcBall.setBounds(width, height);\n adjust_pan_speed(width,height);\n }\n @Override\n public void mousePressed(MouseEvent mouseEvent) {\n switch (mouseEvent.getButton()) {\n case MouseEvent.BUTTON1: // Left Mouse\n Point MousePt = mouseEvent.getPoint();\n LastRot.set(model_matrix);\n arcBall.click(MousePt);\n default:\n return;\n }\n }\n @Override\n public void mouseDragged(MouseEvent mouseEvent) {\n switch (mouseEvent.getButton()) {\n case MouseEvent.BUTTON1: // Left Mouse\n // Update the model matrix\n Point MousePt = mouseEvent.getPoint();\n Quat4f ThisQuat = new Quat4f();\n arcBall.drag(MousePt, ThisQuat);\n model_matrix.setRotation(ThisQuat);\n model_matrix.mul(model_matrix, LastRot);\n break;\n case MouseEvent.BUTTON2: // Middle Mouse\n System.out.printf(\"TODO: PANNING \\n\");\n break;\n default:\n return;\n }\n // Finally refresh the OpenGL window\n canvas.display();\n }\n @Override\n public void mouseClicked(MouseEvent event) {\n if (event.getClickCount() == 2) {\n System.out.println(\"double clicked\");\n }\n }\n @Override\n public void mouseWheelMoved(MouseWheelEvent e){\n setScale( getScale()*(1 + (scale_move_ratio*e.getWheelRotation()) ));\n canvas.display();\n }\n /**\n * The math to implementing ArcBall functionality\n */\n class ArcBallHelper {\n private static final float Epsilon = 1.0e-5f;\n Vector3f StVec; //Saved click vector\n Vector3f EnVec; //Saved drag vector\n float adjustWidth; //Mouse bounds width\n float adjustHeight; //Mouse bounds height\n public ArcBallHelper(float NewWidth, float NewHeight) {\n StVec = new Vector3f();\n EnVec = new Vector3f();\n setBounds(NewWidth, NewHeight);\n }\n public void mapToSphere(Point point, Vector3f vector) {\n //Copy paramter into temp point\n Vector2f tempPoint = new Vector2f(point.x, point.y);\n //Adjust point coords and scale down to range of [-1 ... 1]\n tempPoint.x = (tempPoint.x * this.adjustWidth) - 1.0f;\n tempPoint.y = 1.0f - (tempPoint.y * this.adjustHeight);\n //Compute the square of the length of the vector to the point from the center\n float length = (tempPoint.x * tempPoint.x) + (tempPoint.y * tempPoint.y);\n //If the point is mapped outside of the sphere... (length > radius squared)\n if (length > 1.0f) {\n //Compute a normalizing factor (radius / sqrt(length))\n float norm = (float) (1.0 / Math.sqrt(length));\n //Return the \"normalized\" vector, a point on the sphere\n vector.x = tempPoint.x * norm;\n vector.y = tempPoint.y * norm;\n vector.z = 0.0f;\n } else //Else it's on the inside\n {\n //Return a vector to a point mapped inside the sphere sqrt(radius squared - length)\n vector.x = tempPoint.x;\n vector.y = tempPoint.y;\n vector.z = (float) Math.sqrt(1.0f - length);\n }\n }\n public void setBounds(float NewWidth, float NewHeight) {\n assert((NewWidth > 1.0f) && (NewHeight > 1.0f));\n //Set adjustment factor for width/height\n adjustWidth = 1.0f / ((NewWidth - 1.0f) * 0.5f);\n adjustHeight = 1.0f / ((NewHeight - 1.0f) * 0.5f);\n }\n //Mouse down\n public void click(Point NewPt) {\n mapToSphere(NewPt, this.StVec);\n }\n //Mouse drag, calculate rotation\n public void drag(Point NewPt, Quat4f NewRot) {\n //Map the point to the sphere\n this.mapToSphere(NewPt, EnVec);\n //Return the quaternion equivalent to the rotation\n if (NewRot != null) {\n Vector3f Perp = new Vector3f();\n //Compute the vector perpendicular to the begin and end vectors\n Perp.cross(StVec,EnVec);\n //Compute the length of the perpendicular vector\n if (Perp.length() > Epsilon) //if its non-zero\n {\n //We're ok, so return the perpendicular vector as the transform after all\n NewRot.x = Perp.x;\n NewRot.y = Perp.y;\n NewRot.z = Perp.z;\n //In the quaternion values, w is cosine (theta / 2), where theta is rotation angle\n NewRot.w = StVec.dot(EnVec);\n } else //if its zero\n {\n //The begin and end vectors coincide, so return an identity transform\n NewRot.x = NewRot.y = NewRot.z = NewRot.w = 0.0f;\n }\n }\n }\n }\n}"}}},{"rowIdx":1244,"cells":{"answer":{"kind":"string","value":"package pair;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.BiPredicate;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\nimport java.util.function.ToDoubleBiFunction;\nimport java.util.function.ToDoubleFunction;\nimport java.util.function.ToIntBiFunction;\nimport java.util.function.ToIntFunction;\nimport java.util.function.ToLongBiFunction;\nimport java.util.function.ToLongFunction;\nimport java.util.function.UnaryOperator;\npublic class Pair {\n public static Pair make(final A left, final B right) {\n return new Pair<>(left, right);\n }\n public static Pair of(final A item) {\n return make(item, item);\n }\n public final A left;\n public final B right;\n public final A left() {\n return left;\n }\n public final B right() {\n return right;\n }\n public final Pair invert() {\n return Pair.make(right, left);\n }\n protected Pair(final A a, final B b) {\n left = a;\n right = b;\n }\n public R intoFun(final BiFunction fun) {\n return fun.apply(left, right);\n }\n public void intoCon(final BiConsumer fun) {\n fun.accept(left, right);\n }\n public R intoFun(final Function, R> fun) {\n return fun.apply(this);\n }\n public void intoCon(final Consumer> fun) {\n fun.accept(this);\n }\n public double intoDouble(final ToDoubleFunction> fun) {\n return fun.applyAsDouble(this);\n }\n public double intoDouble(final ToDoubleBiFunction fun) {\n return fun.applyAsDouble(left, right);\n }\n public int intoInt(final ToIntFunction> fun) {\n return fun.applyAsInt(this);\n }\n public int intoInt(final ToIntBiFunction fun) {\n return fun.applyAsInt(left, right);\n }\n public long intoLong(final ToLongFunction> fun) {\n return fun.applyAsLong(this);\n }\n public long intoLong(final ToLongBiFunction fun) {\n return fun.applyAsLong(left, right);\n }\n public Pair intoPair(final UnaryOperator> fun) {\n return fun.apply(this);\n }\n public boolean intoPred(final Predicate> fun) {\n return fun.test(this);\n }\n public boolean intoPred(final BiPredicate fun) {\n return fun.test(left, right);\n }\n public Pair mapLeft(final Function fun) {\n return Pair.make(fun.apply(left), right);\n }\n public Pair mapRight(final Function fun) {\n return Pair.make(left, fun.apply(right));\n }\n public Pair mapLeft(final R neoLiberal) {\n return Pair.make(neoLiberal, right);\n }\n public Pair replaceLeft(final A neoLiberal) {\n return Pair.make(neoLiberal, right);\n }\n public Pair mapRight(final R altRight) {\n return Pair.make(left, altRight);\n }\n public Pair replaceRight(final B altRight) {\n return Pair.make(left, altRight);\n }\n public static final class F {\n public static final Function> partialRight(\n final B right) {\n return left -> Pair.make(left, right);\n }\n public static final Function> partialLeft(\n final A left) {\n return right -> Pair.make(left, right);\n }\n public static final Function, Pair> mapLeft(\n final Function fun) {\n return pair -> pair.mapLeft(fun);\n }\n public static final Function, Pair> mapRight(\n final Function fun) {\n return pair -> pair.mapRight(fun);\n }\n public static final Function, Pair> mapLeft(\n final R neoLiberal) {\n return pair -> pair.mapLeft(neoLiberal);\n }\n public static final Function, Pair> mapRight(\n final R altRight) {\n return pair -> pair.mapRight(altRight);\n }\n public static final UnaryOperator> replaceLeft(\n A neoLiberal) {\n return pair -> pair.replaceLeft(neoLiberal);\n }\n public static final UnaryOperator> replaceRight(\n B altRight) {\n return pair -> pair.replaceRight(altRight);\n }\n public static final Function, R> intoFun(\n final BiFunction fun) {\n return pair -> pair.intoFun(fun);\n }\n public static final UnaryOperator> intoPair(\n final UnaryOperator> fun) {\n return pair -> pair.intoFun(fun);\n }\n public static final ToDoubleFunction> intoDouble(\n final ToDoubleFunction> fun) {\n return pair -> pair.intoDouble(fun);\n }\n public static final ToDoubleFunction> intoDouble(\n final ToDoubleBiFunction fun) {\n return pair -> pair.intoDouble(fun);\n }\n public static final Consumer> intoCon(\n final BiConsumer fun) {\n return pair -> pair.intoCon(fun);\n }\n public static final Predicate> intoPred(\n final BiPredicate pred) {\n return pair -> pair.intoPred(pred);\n }\n }\n}"}}},{"rowIdx":1245,"cells":{"answer":{"kind":"string","value":"package org.jpos.iso;\nimport org.jpos.core.Configurable;\nimport org.jpos.core.Configuration;\nimport org.jpos.core.ConfigurationException;\nimport org.jpos.util.*;\nimport java.io.EOFException;\nimport java.io.IOException;\nimport java.io.InterruptedIOException;\nimport java.io.PrintStream;\nimport java.lang.ref.WeakReference;\nimport java.net.*;\nimport java.util.*;\n/**\n * Accept ServerChannel sessions and forwards them to ISORequestListeners\n * @author Alejandro P. Revilla\n * @author Bharavi Gade\n * @version $Revision$ $Date$\n */\npublic class ISOServer extends Observable\n implements LogSource, Runnable, Observer, ISOServerMBean, Configurable,\n Loggeable, ISOServerSocketFactory\n{\n int port;\n protected ISOChannel clientSideChannel;\n ISOPackager clientPackager;\n protected Collection clientOutgoingFilters, clientIncomingFilters, listeners;\n ThreadPool pool;\n public static final int DEFAULT_MAX_THREADS = 100;\n public static final String LAST = \":last\";\n String name;\n protected long lastTxn = 0l;\n protected Logger logger;\n protected String realm;\n protected String realmChannel;\n protected ISOServerSocketFactory socketFactory = null;\n public static final int CONNECT = 0;\n public static final int SIZEOF_CNT = 1;\n private int[] cnt;\n private String[] allow;\n private InetAddress bindAddr;\n private int backlog;\n protected Configuration cfg;\n private boolean shutdown = false;\n private ServerSocket serverSocket;\n private Map channels;\n protected boolean ignoreISOExceptions;\n /**\n * @param port port to listen\n * @param clientSide client side ISOChannel (where we accept connections)\n * @param pool ThreadPool (created if null)\n */\n public ISOServer(int port, ServerChannel clientSide, ThreadPool pool) {\n super();\n this.port = port;\n this.clientSideChannel = clientSide;\n this.clientPackager = clientSide.getPackager();\n if (clientSide instanceof FilteredChannel) {\n FilteredChannel fc = (FilteredChannel) clientSide;\n this.clientOutgoingFilters = fc.getOutgoingFilters();\n this.clientIncomingFilters = fc.getIncomingFilters();\n }\n this.pool = (pool == null) ?\n new ThreadPool (1, DEFAULT_MAX_THREADS) : pool;\n listeners = new Vector();\n name = \"\";\n channels = new HashMap();\n cnt = new int[SIZEOF_CNT];\n }\n protected Session createSession (ServerChannel channel) {\n return new Session (channel);\n }\n protected class Session implements Runnable, LogSource {\n ServerChannel channel;\n String realm;\n protected Session(ServerChannel channel) {\n this.channel = channel;\n realm = ISOServer.this.getRealm() + \".session\";\n }\n public void run() {\n setChanged ();\n notifyObservers ();\n if (channel instanceof BaseChannel) {\n LogEvent ev = new LogEvent (this, \"session-start\");\n Socket socket = ((BaseChannel)channel).getSocket ();\n realm = realm + \"/\" + socket.getInetAddress().getHostAddress() + \":\"\n + socket.getPort();\n try {\n checkPermission (socket, ev);\n } catch (ISOException e) {\n try {\n int delay = 1000 + new Random().nextInt (4000);\n ev.addMessage (e.getMessage());\n ev.addMessage (\"delay=\" + delay);\n ISOUtil.sleep (delay);\n socket.close ();\n } catch (IOException ioe) {\n ev.addMessage (ioe);\n }\n return;\n } finally {\n Logger.log (ev);\n }\n }\n try {\n for (;;) {\n try {\n ISOMsg m = channel.receive();\n lastTxn = System.currentTimeMillis();\n Iterator iter = listeners.iterator();\n while (iter.hasNext())\n if (((ISORequestListener)iter.next()).process\n (channel, m))\n break;\n }\n catch (ISOFilter.VetoException e) {\n Logger.log (new LogEvent (this, \"VetoException\", e.getMessage()));\n }\n catch (ISOException e) {\n if (ignoreISOExceptions) {\n Logger.log (new LogEvent (this, \"ISOException\", e.getMessage()));\n } else\n throw e;\n }\n }\n } catch (EOFException e) {\n // Logger.log (new LogEvent (this, \"session-warning\", \"\"));\n } catch (SocketException e) {\n // if (!shutdown)\n // Logger.log (new LogEvent (this, \"session-warning\", e));\n } catch (InterruptedIOException e) {\n // nothing to log\n } catch (Throwable e) {\n Logger.log (new LogEvent (this, \"session-error\", e));\n }\n try {\n channel.disconnect();\n } catch (IOException ex) {\n Logger.log (new LogEvent (this, \"session-error\", ex));\n }\n Logger.log (new LogEvent (this, \"session-end\"));\n }\n public void setLogger (Logger logger, String realm) {\n }\n public String getRealm () {\n return realm;\n }\n public Logger getLogger() {\n return ISOServer.this.getLogger();\n }\n public void checkPermission (Socket socket, LogEvent evt)\n throws ISOException\n {\n if (allow != null && allow.length > 0) {\n String ip = socket.getInetAddress().getHostAddress ();\n for (int i=0; i 0 ? \" backlog=\"+backlog : \"\")\n ));\n while (!shutdown) {\n try {\n if (pool.getAvailableCount() <= 0) {\n try {\n serverSocket.close();\n } catch (IOException e){\n Logger.log (new LogEvent (this, \"iso-server\", e));\n relax();\n }\n for (int i=0; pool.getIdleCount() == 0; i++) {\n if (shutdown) break serverLoop;\n if (i % 240 == 0 && cfg.getBoolean(\"pool-exhaustion-warning\", true)) {\n LogEvent evt = new LogEvent (this, \"warn\");\n evt.addMessage (\n \"pool exhausted \" + serverSocket.toString()\n );\n evt.addMessage (pool);\n Logger.log (evt);\n }\n ISOUtil.sleep (250);\n }\n serverSocket = socketFactory.createServerSocket(port);\n }\n channel = (ServerChannel) clientSideChannel.clone();\n channel.accept (serverSocket);\n if ((cnt[CONNECT]++) % 100 == 0)\n purgeChannels ();\n WeakReference wr = new WeakReference (channel);\n channels.put (channel.getName(), wr);\n channels.put (LAST, wr);\n pool.execute (createSession(channel));\n setChanged ();\n notifyObservers (this);\n if (channel instanceof Observable)\n ((Observable)channel).addObserver (this);\n } catch (SocketException e) {\n if (!shutdown) {\n Logger.log (new LogEvent (this, \"iso-server\", e));\n relax();\n continue serverLoop;\n }\n } catch (IOException e) {\n Logger.log (new LogEvent (this, \"iso-server\", e));\n relax();\n }\n }\n } catch (Throwable e) {\n Logger.log (new LogEvent (this, \"iso-server\", e));\n relax();\n }\n }\n }\n private void relax() {\n try {\n Thread.sleep (5000);\n } catch (InterruptedException e) { }\n }\n /**\n * associates this ISOServer with a name using NameRegistrar\n * @param name name to register\n * @see NameRegistrar\n */\n public void setName (String name) {\n this.name = name;\n NameRegistrar.register (\"server.\"+name, this);\n }\n /**\n * @return ISOServer instance with given name.\n * @throws NameRegistrar.NotFoundException;\n * @see NameRegistrar\n */\n public static ISOServer getServer (String name)\n throws NameRegistrar.NotFoundException\n {\n return (ISOServer) NameRegistrar.get (\"server.\"+name);\n }\n /**\n * @return this ISOServer's name (\"\" if no name was set)\n */\n public String getName() {\n return this.name;\n }\n public void setLogger (Logger logger, String realm) {\n this.logger = logger;\n this.realm = realm;\n this.realmChannel = realm + \".channel\";\n }\n public String getRealm () {\n return realm;\n }\n public Logger getLogger() {\n return logger;\n }\n public void update(Observable o, Object arg) {\n setChanged ();\n notifyObservers (arg);\n }\n /**\n * Gets the ISOClientSocketFactory (may be null)\n * @see ISOClientSocketFactory\n * @since 1.3.3\n */\n public ISOServerSocketFactory getSocketFactory() {\n return socketFactory;\n }\n /**\n * Sets the specified Socket Factory to create sockets\n * @param socketFactory the ISOClientSocketFactory\n * @see ISOClientSocketFactory\n * @since 1.3.3\n */\n public void setSocketFactory(ISOServerSocketFactory socketFactory) {\n this.socketFactory = socketFactory;\n }\n public int getPort () {\n return port;\n }\n public void resetCounters () {\n cnt = new int[SIZEOF_CNT];\n lastTxn = 0l;\n }\n /**\n * @return number of connections accepted by this server\n */\n public int getConnectionCount () {\n return cnt[CONNECT];\n }\n // ThreadPoolMBean implementation (delegate calls to pool)\n public int getJobCount () {\n return pool.getJobCount();\n }\n public int getPoolSize () {\n return pool.getPoolSize();\n }\n public int getMaxPoolSize () {\n return pool.getMaxPoolSize();\n }\n public int getIdleCount() {\n return pool.getIdleCount();\n }\n public int getPendingCount () {\n return pool.getPendingCount();\n }\n public int getActiveConnections () {\n return pool.getActiveCount();\n }\n /**\n * @return most recently connected ISOChannel or null\n */\n public ISOChannel getLastConnectedISOChannel () {\n return getISOChannel (LAST);\n }\n /**\n * @return ISOChannel under the given name\n */\n public ISOChannel getISOChannel (String name) {\n WeakReference ref = (WeakReference) channels.get (name);\n if (ref != null)\n return (ISOChannel) ref.get ();\n return null;\n }\n public void setConfiguration (Configuration cfg) throws ConfigurationException {\n this.cfg = cfg;\n allow = cfg.getAll (\"allow\");\n backlog = cfg.getInt (\"backlog\", 0);\n ignoreISOExceptions = cfg.getBoolean(\"ignore-iso-exceptions\");\n String ip = cfg.get (\"bind-address\", null);\n if (ip != null) {\n try {\n bindAddr = InetAddress.getByName (ip);\n } catch (UnknownHostException e) {\n throw new ConfigurationException (\"Invalid bind-address \" + ip, e);\n }\n }\n if (socketFactory == null)\n socketFactory = this;\n if (socketFactory != this && socketFactory instanceof Configurable) {\n ((Configurable)socketFactory).setConfiguration (cfg);\n }\n }\n public String getISOChannelNames () {\n StringBuilder sb = new StringBuilder ();\n Iterator iter = channels.entrySet().iterator();\n for (int i=0; iter.hasNext(); i++) {\n Map.Entry entry = (Map.Entry) iter.next();\n WeakReference ref = (WeakReference) entry.getValue();\n ISOChannel c = (ISOChannel) ref.get ();\n if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) {\n if (i > 0)\n sb.append (' ');\n sb.append (entry.getKey());\n }\n }\n return sb.toString();\n }\n public String getCountersAsString () {\n StringBuilder sb = new StringBuilder ();\n int cnt[] = getCounters();\n sb.append (\"connected=\");\n sb.append (Integer.toString(cnt[0]));\n sb.append (\", rx=\");\n sb.append (Integer.toString(cnt[0]));\n sb.append (\", tx=\");\n sb.append (Integer.toString(cnt[1]));\n sb.append (\", last=\");\n sb.append (lastTxn);\n if (lastTxn > 0) {\n sb.append (\", idle=\");\n sb.append(System.currentTimeMillis() - lastTxn);\n sb.append (\"ms\");\n }\n return sb.toString();\n }\n public int[] getCounters()\n {\n Iterator iter = channels.entrySet().iterator();\n int[] cnt = new int[3];\n cnt[2] = 0;\n for (int i=0; iter.hasNext(); i++) {\n Map.Entry entry = (Map.Entry) iter.next();\n WeakReference ref = (WeakReference) entry.getValue();\n ISOChannel c = (ISOChannel) ref.get ();\n if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) {\n cnt[2]++;\n if (c instanceof BaseChannel) {\n int[] cc = ((BaseChannel)c).getCounters();\n cnt[0] += cc[ISOChannel.RX];\n cnt[1] += cc[ISOChannel.TX];\n }\n }\n }\n return cnt;\n }\n public int getTXCounter() {\n int cnt[] = getCounters();\n return cnt[1];\n }\n public int getRXCounter() {\n int cnt[] = getCounters();\n return cnt[0];\n }\n public int getConnections () {\n int cnt[] = getCounters();\n return cnt[2];\n }\n public long getLastTxnTimestampInMillis() {\n return lastTxn;\n }\n public long getIdleTimeInMillis() {\n return lastTxn > 0L ? System.currentTimeMillis() - lastTxn : -1L;\n }\n public String getCountersAsString (String isoChannelName) {\n ISOChannel channel = getISOChannel(isoChannelName);\n StringBuffer sb = new StringBuffer();\n if (channel instanceof BaseChannel) {\n int[] counters = ((BaseChannel)channel).getCounters();\n append (sb, \"rx=\", counters[ISOChannel.RX]);\n append (sb, \", tx=\", counters[ISOChannel.TX]);\n append (sb, \", connects=\", counters[ISOChannel.CONNECT]);\n }\n return sb.toString();\n }\n public void dump (PrintStream p, String indent) {\n p.println (indent + getCountersAsString());\n Iterator iter = channels.entrySet().iterator();\n String inner = indent + \" \";\n for (int i=0; iter.hasNext(); i++) {\n Map.Entry entry = (Map.Entry) iter.next();\n WeakReference ref = (WeakReference) entry.getValue();\n ISOChannel c = (ISOChannel) ref.get ();\n if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) {\n if (c instanceof BaseChannel) {\n StringBuilder sb = new StringBuilder ();\n int[] cc = ((BaseChannel)c).getCounters();\n sb.append (inner);\n sb.append (entry.getKey());\n sb.append (\": rx=\");\n sb.append (Integer.toString (cc[ISOChannel.RX]));\n sb.append (\", tx=\");\n sb.append (Integer.toString (cc[ISOChannel.TX]));\n sb.append (\", last=\");\n sb.append (Long.toString(lastTxn));\n p.println (sb.toString());\n }\n }\n }\n }\n private void append (StringBuffer sb, String name, int value) {\n sb.append (name);\n sb.append (value);\n }\n}"}}},{"rowIdx":1246,"cells":{"answer":{"kind":"string","value":"package com.intellij.codeInspection.varScopeCanBeNarrowed;\nimport com.intellij.codeInsight.daemon.GroupNames;\nimport com.intellij.codeInspection.InspectionManager;\nimport com.intellij.codeInspection.LocalQuickFix;\nimport com.intellij.codeInspection.ProblemDescriptor;\nimport com.intellij.codeInspection.ProblemHighlightType;\nimport com.intellij.codeInspection.ex.BaseLocalInspectionTool;\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.editor.Editor;\nimport com.intellij.openapi.editor.ScrollType;\nimport com.intellij.openapi.fileEditor.FileEditorManager;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.psi.*;\nimport com.intellij.psi.codeStyle.CodeStyleManager;\nimport com.intellij.psi.codeStyle.VariableKind;\nimport com.intellij.psi.controlFlow.*;\nimport com.intellij.psi.search.GlobalSearchScope;\nimport com.intellij.psi.search.LocalSearchScope;\nimport com.intellij.psi.search.PsiSearchHelper;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.intellij.psi.util.PsiUtil;\nimport com.intellij.refactoring.util.RefactoringUtil;\nimport com.intellij.util.IJSwingUtilities;\nimport com.intellij.util.IncorrectOperationException;\nimport com.intellij.util.containers.HashSet;\nimport java.util.*;\n/**\n * @author ven\n */\npublic class FieldCanBeLocalInspection extends BaseLocalInspectionTool {\n private static final Logger LOG = Logger.getInstance(\"#com.intellij.codeInspection.varScopeCanBeNarrowed.FieldCanBeLocalInspection\");\n public static final String SHORT_NAME = \"FieldCanBeLocal\";\n public String getGroupDisplayName() {\n return GroupNames.CLASSLAYOUT_GROUP_NAME;\n }\n public String getDisplayName() {\n return \"Field can be local\";\n }\n public String getShortName() {\n return SHORT_NAME;\n }\n public ProblemDescriptor[] checkClass(PsiClass aClass, InspectionManager manager, boolean isOnTheFly) {\n PsiManager psiManager = aClass.getManager();\n final Set candidates = new LinkedHashSet();\n final PsiClass topLevelClass = PsiUtil.getTopLevelClass(aClass);\n if (topLevelClass == null) return null;\n final PsiField[] fields = aClass.getFields();\n NextField:\n for (PsiField field : fields) {\n if (field.hasModifierProperty(PsiModifier.PRIVATE)) {\n final PsiReference[] refs = psiManager.getSearchHelper().findReferences(field, GlobalSearchScope.allScope(psiManager.getProject()),\n false);\n for (PsiReference ref : refs) {\n PsiElement element = ref.getElement();\n while (element != null) {\n if (element instanceof PsiMethod) {\n candidates.add(field);\n continue NextField;\n }\n element = PsiTreeUtil.getParentOfType(element, PsiMember.class);\n }\n continue NextField;\n }\n }\n }\n topLevelClass.accept(new PsiRecursiveElementVisitor() {\n public void visitElement(PsiElement element) {\n if (candidates.size() > 0) super.visitElement(element);\n }\n public void visitMethod(PsiMethod method) {\n super.visitMethod(method);\n final PsiCodeBlock body = method.getBody();\n if (body != null) {\n try {\n final ControlFlow controlFlow = ControlFlowFactory.getControlFlow(body, AllVariablesControlFlowPolicy.getInstance());\n final List readBeforeWrite = ControlFlowUtil.getReadBeforeWrite(controlFlow);\n for (Iterator iterator = readBeforeWrite.iterator(); iterator.hasNext();) {\n final PsiElement resolved = iterator.next().resolve();\n if (resolved instanceof PsiField) {\n final PsiField field = (PsiField)resolved;\n candidates.remove(field);\n }\n }\n }\n catch (AnalysisCanceledException e) {\n candidates.clear();\n }\n }\n }\n });\n if (candidates.isEmpty()) return null;\n ProblemDescriptor[] result = new ProblemDescriptor[candidates.size()];\n int i = 0;\n for (Iterator iterator = candidates.iterator(); iterator.hasNext(); i++) {\n PsiField field = iterator.next();\n final String message = \"Field can be converted to one or more local variables.\";\n result[i] = manager.createProblemDescriptor(field, message, new MyQuickFix(field), ProblemHighlightType.GENERIC_ERROR_OR_WARNING);\n }\n return result;\n }\n private static class MyQuickFix implements LocalQuickFix {\n private PsiField myField;\n public MyQuickFix(final PsiField field) {\n myField = field;\n }\n public String getName() {\n return \"Convert to local\";\n }\n public void applyFix(Project project, ProblemDescriptor descriptor) {\n if (!myField.isValid()) return; //weird. should not get here when field becomes invalid\n PsiManager manager = PsiManager.getInstance(project);\n PsiSearchHelper helper = manager.getSearchHelper();\n Set methodSet = new HashSet();\n final PsiReference[] allRefs = helper.findReferences(myField, GlobalSearchScope.allScope(project), false);\n for (PsiReference ref : allRefs) {\n if (ref instanceof PsiReferenceExpression) {\n final PsiMethod method = PsiTreeUtil.getParentOfType((PsiReferenceExpression)ref, PsiMethod.class);\n LOG.assertTrue(method != null);\n methodSet.add(method);\n }\n }\n PsiElement newCaretPosition = null;\n for (PsiMethod method : methodSet) {\n final PsiReference[] refs = helper.findReferences(myField, new LocalSearchScope(method), true);\n LOG.assertTrue(refs.length > 0);\n Set refsSet = new HashSet(Arrays.asList(refs));\n PsiCodeBlock anchorBlock = findAnchorBlock(refs);\n LOG.assertTrue(anchorBlock != null);\n final PsiElementFactory elementFactory = manager.getElementFactory();\n final CodeStyleManager styleManager = manager.getCodeStyleManager();\n final String propertyName = styleManager.variableNameToPropertyName(myField.getName(), VariableKind.FIELD);\n String localName = styleManager.propertyNameToVariableName(propertyName, VariableKind.LOCAL_VARIABLE);\n localName = RefactoringUtil.suggestUniqueVariableName(localName, anchorBlock, myField);\n try {\n final PsiElement anchor = getAnchorElement(anchorBlock, refs);\n final PsiElement newDeclaration;\n if (anchor instanceof PsiExpressionStatement &&\n ((PsiExpressionStatement)anchor).getExpression() instanceof PsiAssignmentExpression) {\n final PsiAssignmentExpression expression = (PsiAssignmentExpression)((PsiExpressionStatement)anchor).getExpression();\n if (expression.getLExpression() instanceof PsiReferenceExpression &&\n ((PsiReferenceExpression)expression.getLExpression()).isReferenceTo(myField)) {\n final PsiExpression initializer = expression.getRExpression();\n final PsiDeclarationStatement decl = elementFactory.createVariableDeclarationStatement(localName, myField.getType(), initializer);\n newDeclaration = anchor.replace(decl);\n refsSet.remove(expression.getLExpression());\n retargetReferences(elementFactory, localName, refsSet);\n }\n else {\n newDeclaration = addDeclarationWithoutInitializerAndRetargetReferences(elementFactory, localName, anchorBlock, anchor, refsSet);\n }\n } else {\n newDeclaration = addDeclarationWithoutInitializerAndRetargetReferences(elementFactory, localName, anchorBlock, anchor, refsSet);\n }\n if (newCaretPosition == null) {\n newCaretPosition = newDeclaration;\n }\n }\n catch (IncorrectOperationException e) {\n LOG.error(e);\n }\n }\n if (newCaretPosition != null) {\n final PsiFile psiFile = myField.getContainingFile();\n final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();\n if (editor != null && IJSwingUtilities.hasFocus(editor.getComponent())) {\n final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());\n if (file == psiFile) {\n editor.getCaretModel().moveToOffset(newCaretPosition.getTextOffset());\n editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);\n }\n }\n }\n try {\n myField.normalizeDeclaration();\n myField.delete();\n }\n catch (IncorrectOperationException e) {\n LOG.error(e);\n }\n }\n private void retargetReferences(final PsiElementFactory elementFactory, final String localName, final Set refs)\n throws IncorrectOperationException {\n final PsiReferenceExpression refExpr = (PsiReferenceExpression)elementFactory.createExpressionFromText(localName, null);\n for (PsiReference ref : refs) {\n if (ref instanceof PsiReferenceExpression) {\n ((PsiReferenceExpression)ref).replace(refExpr);\n }\n }\n }\n private PsiElement addDeclarationWithoutInitializerAndRetargetReferences(final PsiElementFactory elementFactory,\n final String localName,\n final PsiCodeBlock anchorBlock, final PsiElement anchor,\n final Set refs)\n throws IncorrectOperationException {\n final PsiElement newDeclaration;\n final PsiDeclarationStatement decl = elementFactory.createVariableDeclarationStatement(localName, myField.getType(), null);\n newDeclaration = anchorBlock.addBefore(decl, anchor);\n retargetReferences(elementFactory, localName, refs);\n return newDeclaration;\n }\n public String getFamilyName() {\n return getName();\n }\n private static PsiElement getAnchorElement(final PsiCodeBlock anchorBlock, final PsiReference[] refs) {\n PsiElement firstElement = null;\n for (PsiReference reference : refs) {\n final PsiElement element = reference.getElement();\n if (firstElement == null || firstElement.getTextRange().getStartOffset() > element.getTextRange().getStartOffset()) {\n firstElement = element;\n }\n }\n LOG.assertTrue(firstElement != null);\n while (firstElement.getParent() != anchorBlock) {\n firstElement = firstElement.getParent();\n }\n return firstElement;\n }\n private static PsiCodeBlock findAnchorBlock(final PsiReference[] refs) {\n PsiCodeBlock result = null;\n for (PsiReference psiReference : refs) {\n final PsiElement element = psiReference.getElement();\n PsiCodeBlock block = PsiTreeUtil.getParentOfType(element, PsiCodeBlock.class);\n if (result == null) {\n result = block;\n }\n else {\n final PsiElement commonParent = PsiTreeUtil.findCommonParent(result, block);\n result = PsiTreeUtil.getParentOfType(commonParent, PsiCodeBlock.class, false);\n }\n }\n return result;\n }\n }\n}"}}},{"rowIdx":1247,"cells":{"answer":{"kind":"string","value":"package ca.bc.gov.restrictions;\nimport java.security.Principal;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.nuxeo.ecm.core.api.security.ACE;\nimport org.nuxeo.ecm.core.api.security.ACL;\nimport org.nuxeo.ecm.core.api.security.ACP;\nimport org.nuxeo.ecm.core.api.security.Access;\nimport org.nuxeo.ecm.core.api.security.SecurityConstants;\nimport org.nuxeo.ecm.core.model.Document;\nimport org.nuxeo.ecm.core.security.AbstractSecurityPolicy;\nimport ca.bc.gov.utils.CustomSecurityConstants;\n/**\n * Language recorders policies\n */\npublic class LanguageRecorders extends AbstractSecurityPolicy {\n private static ArrayList allowedDocumentTypes = new ArrayList();\n private Boolean hasPermissionInACP(ACP mergedAcp, List additionalPrincipalsList, String permission) {\n for (ACL acl : mergedAcp.getACLs()) {\n for (ACE ace : acl.getACEs()) {\n if (ace.isGranted() && additionalPrincipalsList.contains(ace.getUsername()) && ace.getPermission().equals(permission) ) {\n return true;\n }\n }\n }\n return false;\n }\n @Override\n public boolean isRestrictingPermission(String permission) {\n if ( permission.equals(SecurityConstants.ADD_CHILDREN) ||\n permission.equals(SecurityConstants.WRITE) ||\n permission.equals(SecurityConstants.WRITE_PROPERTIES) ||\n permission.equals(CustomSecurityConstants.CAN_ASK_FOR_PUBLISH) ||\n permission.equals(SecurityConstants.REMOVE_CHILDREN) ||\n permission.equals(SecurityConstants.REMOVE)) {\n return true;\n }\n return false;\n }\n @Override\n public Access checkPermission(Document doc, ACP mergedAcp,\n Principal principal, String permission,\n String[] resolvedPermissions, String[] additionalPrincipals) throws SecurityException {\n List resolvedPermissionsList = Arrays.asList(resolvedPermissions);\n List additionalPrincipalsList = Arrays.asList(additionalPrincipals);\n // Skip administrators and system\n if (additionalPrincipalsList.contains(\"administrators\") || principal.equals(\"system\")) {\n return Access.UNKNOWN;\n }\n if (\"BROWSE\".equals(permission)) {\n return Access.UNKNOWN;\n }\n String docType = doc.getType().getName();\n String docTypeParent = null;\n if (doc.getParent() != null) {\n docTypeParent = doc.getParent().getType().getName();\n }\n if ( hasPermissionInACP(mergedAcp, additionalPrincipalsList, CustomSecurityConstants.RECORD) ) {\n if (allowedDocumentTypes.isEmpty()) {\n allowedDocumentTypes.add(\"FVCategories\");\n allowedDocumentTypes.add(\"FVContributors\");\n allowedDocumentTypes.add(\"FVDictionary\");\n allowedDocumentTypes.add(\"FVResources\");\n }\n // Allow adding children and removing children on allowed types\n if (allowedDocumentTypes.contains(docType) && (resolvedPermissionsList.contains(SecurityConstants.ADD_CHILDREN) || resolvedPermissionsList.contains(SecurityConstants.REMOVE_CHILDREN)) ) {\n return Access.GRANT;\n }\n // Allow Publishing, Writing and Removing on allowed document type children\n if (docTypeParent != null && allowedDocumentTypes.contains(docTypeParent) && (resolvedPermissionsList.contains(SecurityConstants.WRITE_PROPERTIES) || resolvedPermissionsList.contains(SecurityConstants.REMOVE) || resolvedPermissionsList.contains(SecurityConstants.WRITE)) ) {\n return Access.GRANT;\n }\n }\n // Recorders can only publish to their allowed types (OK to use groups as this is globally applicable)\n if (additionalPrincipalsList.contains(CustomSecurityConstants.RECORDERS_GROUP) || additionalPrincipalsList.contains(CustomSecurityConstants.RECORDERS_APPROVERS_GROUP)) {\n if (!allowedDocumentTypes.contains(docType) && (resolvedPermissionsList.contains(CustomSecurityConstants.CAN_ASK_FOR_PUBLISH)) ) {\n return Access.DENY;\n }\n }\n return Access.UNKNOWN;\n }\n @Override\n public boolean isExpressibleInQuery(String repositoryName) {\n return false;\n }\n}"}}},{"rowIdx":1248,"cells":{"answer":{"kind":"string","value":"package org.xwiki.tool.spoon;\nimport java.util.List;\nimport java.util.Map;\nimport org.apache.log4j.Level;\nimport spoon.processing.AbstractProcessor;\nimport spoon.processing.Property;\nimport spoon.reflect.code.CtExpression;\nimport spoon.reflect.code.CtInvocation;\n/**\n * Failed the build if some code is calling a forbidden method.\n *\n * @version $Id$\n * @since 9.9RC2\n */\npublic class ForbiddenInvocationProcessor extends AbstractProcessor>\n{\n @Property\n private Map> methods;\n @Override\n public void process(CtInvocation element)\n {\n CtExpression target = element.getTarget();\n if (target != null && target.getType() != null) {\n String type = target.getType().getQualifiedName();\n List methodList = this.methods.get(type);\n if (methodList != null) {\n String method = element.getExecutable().getSimpleName();\n if (methodList.contains(method)) {\n getFactory().getEnvironment().report(this, Level.ERROR, element,\n \"Forbidden call to \" + type + \"#\" + method);\n // Forcing the build to stop\n throw new RuntimeException(\"Forbidden call to \" + type + \"#\" + method);\n }\n }\n }\n }\n}"}}},{"rowIdx":1249,"cells":{"answer":{"kind":"string","value":"package org.xwiki.test.ui.framework;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.NoSuchElementException;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport org.openqa.selenium.support.events.EventFiringWebDriver;\nimport org.xwiki.test.integration.XWikiExecutor;\n/**\n * This is a container for holding all of the information which should persist throughout all of the tests.\n *\n * @version $Id$\n * @since 2.4M1\n */\npublic class PersistentTestContext\n{\n /** This starts and stops the wiki engine. */\n private final XWikiExecutor executor;\n private final WebDriver driver;\n /** Utility methods which should be available to tests and to pages. */\n private final TestUtils util = new TestUtils();\n public PersistentTestContext() throws Exception\n {\n this.executor = new XWikiExecutor(0);\n executor.start();\n // Ensure that we display page source information if an HTML fails to be found, for easier debugging.\n this.driver = new EventFiringWebDriver(new FirefoxDriver()) {\n @Override public WebElement findElement(By by)\n {\n try {\n return super.findElement(by);\n } catch (NoSuchElementException e) {\n throw new NoSuchElementException(e.getMessage() + \" Page source [\" + getPageSource()\n + \"]\", e.getCause());\n }\n }\n };\n }\n public PersistentTestContext(PersistentTestContext toClone)\n {\n this.executor = toClone.executor;\n this.driver = toClone.driver;\n }\n public WebDriver getDriver()\n {\n return this.driver;\n }\n /**\n * @return Utility class with functions not specific to any test or element.\n */\n public TestUtils getUtil()\n {\n return this.util;\n }\n public void shutdown() throws Exception\n {\n driver.close();\n executor.stop();\n }\n /**\n * Get a clone of this context which cannot be stopped by calling shutdown. this is needed so that individual tests\n * don't shutdown when AllTests ware being run.\n */\n public PersistentTestContext getUnstoppable()\n {\n return new PersistentTestContext(this)\n {\n public void shutdown()\n {\n // Do nothing, that's why it's unstoppable.\n }\n };\n }\n}"}}},{"rowIdx":1250,"cells":{"answer":{"kind":"string","value":"package io.github.lonamiwebs.stringlate.git;\nimport android.app.Activity;\nimport org.eclipse.jgit.lib.ProgressMonitor;\nimport io.github.lonamiwebs.stringlate.R;\nimport io.github.lonamiwebs.stringlate.interfaces.ProgressUpdateCallback;\npublic abstract class GitCloneProgressCallback\n implements ProgressUpdateCallback, ProgressMonitor {\n private Activity mActivity;\n private int mCurrentTask, mDone, mWork;\n private long mLastMs;\n private final static long DELAY_PER_UPDATE = 60; // 60ms\n protected GitCloneProgressCallback(Activity activity) {\n mActivity = activity;\n }\n @Override\n final public void beginTask(String title, int totalWork) {\n mCurrentTask++;\n mLastMs = 0;\n mDone = 0;\n mWork = totalWork;\n }\n @Override\n final public void update(int completed) {\n mDone += completed;\n // This method is called way so often, slow it down\n long time = System.currentTimeMillis();\n if (time - mLastMs >= DELAY_PER_UPDATE) {\n mLastMs = time;\n updateProgress();\n }\n }\n @Override\n final public void start(int totalTasks) { /* Total tasks is a liar */ }\n @Override\n final public void endTask() { }\n private void updateProgress() {\n final String title = mActivity.getString(R.string.cloning_repo);\n final String content = mActivity.getString(\n R.string.cloning_repo_progress, getProgress(mCurrentTask, mDone, mWork));\n // TODO This probably can be improved. Some handler to post the result?\n mActivity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n onProgressUpdate(title, content);\n }\n });\n }\n private static float getProgress(int task, float done, float work) {\n // After timing cloning a large repository (F-Droid client) twice and averaging:\n if (work > 0 && task < 5) {\n return getTotalTime(task) + (done / work) * getTime(task);\n } else {\n return getTotalTime(task);\n }\n }\n private static float getTime(int task) {\n switch (task) {\n case 1: return 0.003f;\n case 2: return 0.204f;\n case 3: return 45.74f;\n case 4: return 54.52f;\n default: return 0.00f;\n }\n }\n private static float getTotalTime(int untilTask) {\n switch (untilTask) {\n case 1: return 0.000f;\n case 2: return 0.003f;\n case 3: return 0.207f;\n case 4: return 45.95f;\n default: return 1.00f;\n }\n }\n @Override\n final public boolean isCancelled() {\n return false;\n }\n}"}}},{"rowIdx":1251,"cells":{"answer":{"kind":"string","value":"package be.kuleuven.cs.distrinet.jnome.core.expression.invocation;\nimport static be.kuleuven.cs.distrinet.rejuse.collection.CollectionOperations.exists;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport org.aikodi.chameleon.core.lookup.LookupException;\nimport org.aikodi.chameleon.oo.language.ObjectOrientedLanguage;\nimport org.aikodi.chameleon.oo.type.Type;\nimport org.aikodi.chameleon.oo.type.TypeInstantiation;\nimport org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter;\nimport org.aikodi.chameleon.oo.type.generics.EqualityConstraint;\nimport org.aikodi.chameleon.oo.type.generics.EqualityTypeArgument;\nimport org.aikodi.chameleon.oo.type.generics.ExtendsWildcard;\nimport org.aikodi.chameleon.oo.type.generics.InstantiatedTypeParameter;\nimport org.aikodi.chameleon.oo.type.generics.SuperWildcard;\nimport org.aikodi.chameleon.oo.type.generics.TypeArgument;\nimport org.aikodi.chameleon.oo.type.generics.TypeArgumentWithTypeReference;\nimport org.aikodi.chameleon.oo.type.generics.TypeConstraint;\nimport org.aikodi.chameleon.oo.type.generics.TypeParameter;\nimport org.aikodi.chameleon.oo.type.generics.TypeVariable;\nimport org.aikodi.chameleon.util.Util;\nimport org.aikodi.chameleon.workspace.View;\nimport be.kuleuven.cs.distrinet.jnome.core.language.Java7;\nimport be.kuleuven.cs.distrinet.jnome.core.type.ArrayType;\nimport be.kuleuven.cs.distrinet.jnome.core.type.ArrayTypeReference;\nimport be.kuleuven.cs.distrinet.jnome.core.type.BasicJavaTypeReference;\nimport be.kuleuven.cs.distrinet.jnome.core.type.JavaTypeReference;\nimport be.kuleuven.cs.distrinet.rejuse.logic.ternary.Ternary;\nimport be.kuleuven.cs.distrinet.rejuse.predicate.Predicate;\n/**\n * A = type()\n * F = typeReference()\n *\n * @author Marko van Dooren\n */\npublic abstract class FirstPhaseConstraint extends Constraint {\n /**\n *\n * @param type\n * @param tref\n */\n public FirstPhaseConstraint(JavaTypeReference A, Type F) {\n _A = A;\n _F = F;\n }\n private JavaTypeReference _A;\n public Type A() throws LookupException {\n return _A.getElement();\n }\n public JavaTypeReference ARef() {\n return _A;\n }\n// private JavaTypeReference _typeReference;\n// public JavaTypeReference typeReference() {\n// return _typeReference;\n public Type F() {\n return _F;\n }\n private Type _F;\n public List process() throws LookupException {\n List result = new ArrayList();\n // If A is the type of null, no constraint is implied on Tj.\n Type A = A();\n View view = A.view();\n ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class);\n if(! A.equals(l.getNullType(view.namespace()))) {\n result.addAll(processFirstLevel());\n }\n return result;\n }\n public List processFirstLevel() throws LookupException {\n List result = new ArrayList();\n// Declaration declarator = typeReference().getDeclarator();\n if(F() instanceof TypeVariable && parent().typeParameters().contains(((TypeVariable)F()).parameter())) {\n // Otherwise, if F=Tj, then the constraint Tj :> A is implied.\n result.add(FequalsTj(((TypeVariable)F()).parameter(), ARef()));\n }\n else if(F() instanceof ArrayType) {\n // If F=U[], where the type U involves Tj, then if A is an array type V[], or\n // a type variable with an upper bound that is an array type V[], where V is a\n // reference type, this algorithm is applied recursively to the constraint V< actualsOfF = new ArrayList();\n for(TypeParameter par: F().parameters(TypeParameter.class)) {\n if(par instanceof InstantiatedTypeParameter) {\n actualsOfF.add(((InstantiatedTypeParameter)par).argument());\n }\n else if(par instanceof CapturedTypeParameter) {\n List constraints = ((CapturedTypeParameter) par).constraints();\n if(constraints.size() == 1 && constraints.get(0) instanceof EqualityConstraint) {\n EqualityConstraint eq = (EqualityConstraint) constraints.get(0);\n EqualityTypeArgument arg = language().createEqualityTypeArgument(Util.clone(eq.typeReference()));\n arg.setUniParent(eq);\n actualsOfF.add(arg);\n }\n }\n }\n int i = 0;\n for(TypeArgument typeArgumentOfFormalParameter: actualsOfF) {\n if(typeArgumentOfFormalParameter instanceof EqualityTypeArgument) {\n JavaTypeReference U = (JavaTypeReference) ((EqualityTypeArgument)typeArgumentOfFormalParameter).typeReference();\n if(involvesTypeParameter(U)) {\n caseSSFormalBasic(result, U, i);\n }\n } else if(typeArgumentOfFormalParameter instanceof ExtendsWildcard) {\n JavaTypeReference U = (JavaTypeReference) ((ExtendsWildcard)typeArgumentOfFormalParameter).typeReference();\n if(involvesTypeParameter(U)) {\n caseSSFormalExtends(result, U, i);\n }\n } else if(typeArgumentOfFormalParameter instanceof SuperWildcard) {\n JavaTypeReference U = (JavaTypeReference) ((SuperWildcard)typeArgumentOfFormalParameter).typeReference();\n if(involvesTypeParameter(U)) {\n caseSSFormalSuper(result, U, i);\n }\n }\n i++;\n }\n }\n// else {\n// result.addAll(processSpecifics());\n return result;\n }\n public abstract void caseSSFormalBasic(List result, JavaTypeReference U,\n int index) throws LookupException;\n public abstract void caseSSFormalExtends(List result, JavaTypeReference U,\n int index) throws LookupException;\n public abstract void caseSSFormalSuper(List result, JavaTypeReference U,\n int index) throws LookupException;\n public abstract SecondPhaseConstraint FequalsTj(TypeParameter declarator, JavaTypeReference type);\n public abstract FirstPhaseConstraint Array(JavaTypeReference componentType, Type componentTypeReference);\n// public abstract List processSpecifics() throws LookupException;\n public boolean involvesTypeParameter(JavaTypeReference tref) throws LookupException {\n return ! involvedTypeParameters(tref).isEmpty();\n }\n public boolean involvesTypeParameter(Type type) throws LookupException {\n return ((type instanceof TypeVariable) && (parent().typeParameters().contains(((TypeVariable) type).parameter())))\n || ((type instanceof ArrayType) && (involvesTypeParameter(((ArrayType) type).elementType())))\n || ((type instanceof TypeInstantiation) && (involvesTypeParameter(type.baseType())))\n || exists(type.parameters(TypeParameter.class), object -> (object instanceof InstantiatedTypeParameter)\n && involvesTypeParameter(((InstantiatedTypeParameter) object).argument()));\n }\n public boolean involvesTypeParameter(TypeArgument arg) throws LookupException {\n return (arg instanceof TypeArgumentWithTypeReference) &&\n involvesTypeParameter((JavaTypeReference) ((TypeArgumentWithTypeReference)arg).typeReference());\n }\n public List involvedTypeParameters(JavaTypeReference tref) throws LookupException {\n Predicate predicate =\n object -> parent().typeParameters().contains(object.getDeclarator());\n List list = tref.descendants(BasicJavaTypeReference.class, predicate);\n if((tref instanceof BasicJavaTypeReference) && predicate.eval((BasicJavaTypeReference) tref)) {\n list.add((BasicJavaTypeReference) tref);\n }\n List parameters = new ArrayList();\n for(BasicJavaTypeReference cref: list) {\n parameters.add((TypeParameter) cref.getDeclarator());\n }\n return parameters;\n }\n public Java7 language() throws LookupException {\n return A().language(Java7.class);\n }\n public View view() throws LookupException {\n return A().view();\n }\n protected Type typeWithSameBaseTypeAs(Type example, Collection toBeSearched) {\n Type baseType = example.baseType();\n for(Type type:toBeSearched) {\n if(type.baseType().equals(baseType)) {\n return type;\n }\n }\n return null;\n }\n}"}}},{"rowIdx":1252,"cells":{"answer":{"kind":"string","value":"package org.rstudio.studio.client.workbench.prefs.views;\nimport com.google.gwt.resources.client.ImageResource;\nimport com.google.gwt.user.client.ui.CheckBox;\nimport com.google.inject.Inject;\nimport org.rstudio.core.client.prefs.PreferencesDialogBaseResources;\nimport org.rstudio.core.client.widget.NumericValueWidget;\nimport org.rstudio.studio.client.workbench.prefs.model.RPrefs;\nimport org.rstudio.studio.client.workbench.prefs.model.UIPrefs;\npublic class EditingPreferencesPane extends PreferencesPane\n{\n @Inject\n public EditingPreferencesPane(UIPrefs prefs)\n {\n prefs_ = prefs;\n add(checkboxPref(\"Highlight selected word\", prefs.highlightSelectedWord()));\n add(checkboxPref(\"Highlight selected line\", prefs.highlightSelectedLine()));\n add(checkboxPref(\"Show line numbers\", prefs.showLineNumbers()));\n add(tight(spacesForTab_ = checkboxPref(\"Insert spaces for tab\", prefs.useSpacesForTab())));\n add(indent(tabWidth_ = numericPref(\"Tab width\", prefs.numSpacesForTab())));\n add(tight(showMargin_ = checkboxPref(\"Show margin\", prefs.showMargin())));\n add(indent(marginCol_ = numericPref(\"Margin column\", prefs.printMarginColumn())));\n add(checkboxPref(\"Show whitespace characters\", prefs_.showInvisibles()));\n add(checkboxPref(\"Show indent guides\", prefs_.showIndentGuides()));\n add(checkboxPref(\"Blinking cursor\", prefs_.blinkingCursor()));\n add(checkboxPref(\"Insert matching parens/quotes\", prefs_.insertMatching()));\n add(checkboxPref(\"Auto-indent code after paste\", prefs_.reindentOnPaste()));\n add(checkboxPref(\"Vertically align arguments in auto-indent\", prefs_.verticallyAlignArgumentIndent()));\n add(checkboxPref(\"Soft-wrap R source files\", prefs_.softWrapRFiles()));\n add(checkboxPref(\"Focus console after executing from source\", prefs_.focusConsoleAfterExec()));\n add(checkboxPref(\"Show syntax highlighting in console input\", prefs_.syntaxColorConsole()));\n add(checkboxPref(\"Enable vim editing mode\", prefs_.useVimMode()));\n }\n @Override\n public ImageResource getIcon()\n {\n return PreferencesDialogBaseResources.INSTANCE.iconCodeEditing();\n }\n @Override\n public boolean validate()\n {\n return (!spacesForTab_.getValue() || tabWidth_.validatePositive(\"Tab width\")) &&\n (!showMargin_.getValue() || marginCol_.validate(\"Margin column\"));\n }\n @Override\n public String getName()\n {\n return \"Code Editing\";\n }\n @Override\n protected void initialize(RPrefs prefs)\n {\n }\n private final UIPrefs prefs_;\n private final NumericValueWidget tabWidth_;\n private final NumericValueWidget marginCol_;\n private final CheckBox spacesForTab_;\n private final CheckBox showMargin_;\n}"}}},{"rowIdx":1253,"cells":{"answer":{"kind":"string","value":"package org.activiti.cycle.impl.connector.signavio.transform.pattern;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.activiti.cycle.RepositoryConnector;\nimport org.activiti.cycle.impl.connector.signavio.SignavioPluginDefinition;\nimport org.activiti.cycle.impl.connector.signavio.transform.JsonTransformationException;\nimport org.oryxeditor.server.diagram.Diagram;\nimport org.oryxeditor.server.diagram.DiagramBuilder;\nimport org.oryxeditor.server.diagram.Shape;\nimport org.oryxeditor.server.diagram.StencilType;\n/**\n * @author Falko Menge\n */\npublic class SubProcessExpansion extends OryxTransformation {\n public static final String STENCIL_SUBPROCESS = \"Subprocess\";\n public static final String STENCIL_COLLAPSED_SUBPROCESS = \"CollapsedSubprocess\";\n public static final String PROPERTY_NAME = \"name\";\n public static final String PROPERTY_ENTRY = \"entry\";\n public static final String PROPERTY_IS_CALL_ACTIVITY = \"callacitivity\";\n private RepositoryConnector connector;\n public SubProcessExpansion(RepositoryConnector repositoryConnector) {\n this.connector = repositoryConnector;\n }\n @Override\n public Diagram transform(Diagram diagram) {\n expandSubProcesses(diagram);\n return diagram;\n }\n private void expandSubProcesses(Diagram diagram) {\n List shapes = diagram.getShapes();\n for (Shape shape : shapes) {\n if (STENCIL_COLLAPSED_SUBPROCESS.equals(shape.getStencilId()) && !\"true\".equals(shape.getProperty(PROPERTY_IS_CALL_ACTIVITY))) {\n String subProcessUrl = shape.getProperty(PROPERTY_ENTRY);\n if (subProcessUrl != null && subProcessUrl.length() > 0) {\n String subProcessName = shape.getProperty(PROPERTY_NAME);\n try {\n String subProcessId = getModelIdFromSignavioUrl(subProcessUrl);\n String representationName = SignavioPluginDefinition.CONTENT_REPRESENTATION_ID_JSON;\n String subProcessJson = connector.getContent(subProcessId, representationName).asString();\n Diagram subProcess = DiagramBuilder.parseJson(subProcessJson);\n // FIXME subProcess = new ExtractProcessOfParticipant(\"Process Engine\").transform(subProcess);\n expandSubProcesses(subProcess);\n shape.setStencil(new StencilType(STENCIL_SUBPROCESS));\n ArrayList childShapes = shape.getChildShapes();\n childShapes.addAll(subProcess.getChildShapes());\n } catch (Exception e) {\n throw new JsonTransformationException(\n \"Error while retrieving Sub-Process\"\n + \" '\" + subProcessName + \"'\"\n + \" (URL: \" + subProcessUrl + \").\",\n e);\n }\n }\n }\n }\n }\n public static String getModelIdFromSignavioUrl(String subProcessUrl) throws UnsupportedEncodingException {\n String modelId = null;\n List patterns = new ArrayList();\n patterns.add(Pattern.compile(\"^.*/p/model/(.*)$\"));\n patterns.add(Pattern.compile(\"^.*/p/editor[?]id=(.*)$\")); // workaround for Activiti Modeler\n for (Pattern pattern : patterns) {\n Matcher matcher = pattern.matcher(subProcessUrl);\n if (matcher.matches()) {\n modelId = URLDecoder.decode(matcher.group(1), \"UTF-8\");\n break;\n }\n }\n return modelId;\n }\n}"}}},{"rowIdx":1254,"cells":{"answer":{"kind":"string","value":"package org.openhab.binding.zwave.internal;\nimport java.math.BigDecimal;\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Set;\nimport org.eclipse.smarthome.config.core.ConfigDescription;\nimport org.eclipse.smarthome.config.core.ConfigDescriptionParameter;\nimport org.eclipse.smarthome.config.core.ConfigDescriptionParameter.Type;\nimport org.eclipse.smarthome.config.core.ConfigDescriptionParameterBuilder;\nimport org.eclipse.smarthome.config.core.ConfigDescriptionParameterGroup;\nimport org.eclipse.smarthome.config.core.ConfigDescriptionProvider;\nimport org.eclipse.smarthome.config.core.ConfigDescriptionRegistry;\nimport org.eclipse.smarthome.config.core.ConfigOptionProvider;\nimport org.eclipse.smarthome.config.core.ParameterOption;\nimport org.eclipse.smarthome.core.thing.Thing;\nimport org.eclipse.smarthome.core.thing.ThingRegistry;\nimport org.eclipse.smarthome.core.thing.ThingTypeUID;\nimport org.eclipse.smarthome.core.thing.ThingUID;\nimport org.eclipse.smarthome.core.thing.type.ThingType;\nimport org.eclipse.smarthome.core.thing.type.ThingTypeRegistry;\nimport org.openhab.binding.zwave.ZWaveBindingConstants;\nimport org.openhab.binding.zwave.handler.ZWaveControllerHandler;\nimport org.openhab.binding.zwave.internal.protocol.ZWaveNode;\nimport org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass;\nimport org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass.CommandClass;\nimport org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveUserCodeCommandClass;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.google.common.collect.ImmutableSet;\npublic class ZWaveConfigProvider implements ConfigDescriptionProvider, ConfigOptionProvider {\n private final Logger logger = LoggerFactory.getLogger(ZWaveConfigProvider.class);\n private static ThingRegistry thingRegistry;\n private static ThingTypeRegistry thingTypeRegistry;\n private static ConfigDescriptionRegistry configDescriptionRegistry;\n private static Set zwaveThingTypeUIDList = new HashSet();\n private static List productIndex = new ArrayList();\n private static final Object productIndexLock = new Object();\n // The following is a list of classes that are controllable.\n // This is used to filter endpoints so that when we display a list of nodes/endpoints\n // for configuring associations, we only list endpoints that are useful\n private static final Set controllableClasses = ImmutableSet.of(CommandClass.BASIC,\n CommandClass.SWITCH_BINARY, CommandClass.SWITCH_MULTILEVEL, CommandClass.SWITCH_TOGGLE_BINARY,\n CommandClass.SWITCH_TOGGLE_MULTILEVEL, CommandClass.CHIMNEY_FAN, CommandClass.THERMOSTAT_HEATING,\n CommandClass.THERMOSTAT_MODE, CommandClass.THERMOSTAT_OPERATING_STATE, CommandClass.THERMOSTAT_SETPOINT,\n CommandClass.THERMOSTAT_FAN_MODE, CommandClass.THERMOSTAT_FAN_STATE, CommandClass.FIBARO_FGRM_222);\n protected void setThingRegistry(ThingRegistry thingRegistry) {\n ZWaveConfigProvider.thingRegistry = thingRegistry;\n }\n protected void unsetThingRegistry(ThingRegistry thingRegistry) {\n ZWaveConfigProvider.thingRegistry = null;\n }\n protected void setThingTypeRegistry(ThingTypeRegistry thingTypeRegistry) {\n ZWaveConfigProvider.thingTypeRegistry = thingTypeRegistry;\n }\n protected void unsetThingTypeRegistry(ThingTypeRegistry thingTypeRegistry) {\n ZWaveConfigProvider.thingTypeRegistry = null;\n }\n protected void setConfigDescriptionRegistry(ConfigDescriptionRegistry configDescriptionRegistry) {\n ZWaveConfigProvider.configDescriptionRegistry = configDescriptionRegistry;\n }\n protected void unsetConfigDescriptionRegistry(ConfigDescriptionRegistry configDescriptionRegistry) {\n ZWaveConfigProvider.configDescriptionRegistry = null;\n }\n @Override\n public Collection getConfigDescriptions(Locale locale) {\n logger.debug(\"getConfigDescriptions called\");\n return Collections.emptySet();\n }\n @Override\n public ConfigDescription getConfigDescription(URI uri, Locale locale) {\n if (uri == null) {\n return null;\n }\n if (\"thing\".equals(uri.getScheme()) == false) {\n return null;\n }\n ThingUID thingUID = new ThingUID(uri.getSchemeSpecificPart());\n ThingType thingType = thingTypeRegistry.getThingType(thingUID.getThingTypeUID());\n if (thingType == null) {\n return null;\n }\n // Is this a zwave thing?\n if (!thingUID.getBindingId().equals(ZWaveBindingConstants.BINDING_ID)) {\n return null;\n }\n // And make sure this is a node because we want to get the id off the end...\n if (!thingUID.getId().startsWith(\"node\")) {\n return null;\n }\n int nodeId = Integer.parseInt(thingUID.getId().substring(4));\n Thing thing = getThing(thingUID);\n if (thing == null) {\n return null;\n }\n ThingUID bridgeUID = thing.getBridgeUID();\n // Get the controller for this thing\n Thing bridge = getThing(bridgeUID);\n if (bridge == null) {\n return null;\n }\n // Get its handler and node\n ZWaveControllerHandler handler = (ZWaveControllerHandler) bridge.getHandler();\n ZWaveNode node = handler.getNode(nodeId);\n List groups = new ArrayList();\n List parameters = new ArrayList();\n groups.add(new ConfigDescriptionParameterGroup(\"actions\", \"\", false, \"Actions\", null));\n groups.add(new ConfigDescriptionParameterGroup(\"thingcfg\", \"home\", false, \"Device Configuration\", null));\n parameters.add(ConfigDescriptionParameterBuilder\n .create(ZWaveBindingConstants.CONFIGURATION_POLLPERIOD, Type.INTEGER).withLabel(\"Polling Period\")\n .withDescription(\"Set the minimum polling period for this device
\"\n + \"Note that the polling period may be longer than set since the binding treats \"\n + \"polls as the lowest priority data within the network.\")\n .withDefault(\"1800\").withMinimum(new BigDecimal(15)).withMaximum(new BigDecimal(7200))\n .withGroupName(\"thingcfg\").build());\n // If we support the wakeup class, then add the configuration\n if (node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP) != null) {\n groups.add(new ConfigDescriptionParameterGroup(\"wakeup\", \"sleep\", false, \"Wakeup Configuration\", null));\n parameters.add(ConfigDescriptionParameterBuilder\n .create(ZWaveBindingConstants.CONFIGURATION_WAKEUPINTERVAL, Type.TEXT).withLabel(\"Wakeup Interval\")\n .withDescription(\"Sets the number of seconds that the device will wakeup
\"\n + \"Setting a shorter time will allow openHAB to configure the device more regularly, but may use more battery power.
\"\n + \"Note: This setting does not impact device notifications such as alarms.\")\n .withDefault(\"\").withGroupName(\"wakeup\").build());\n parameters.add(\n ConfigDescriptionParameterBuilder.create(ZWaveBindingConstants.CONFIGURATION_WAKEUPNODE, Type.TEXT)\n .withLabel(\"Wakeup Node\").withAdvanced(true)\n .withDescription(\"Sets the wakeup node to which the device will send notifications.
\"\n + \"This should normally be set to the openHAB controller - \"\n + \"if it isn't, openHAB will not receive notifications when the device wakes up, \"\n + \"and will not be able to configure the device.\")\n .withDefault(\"\").withGroupName(\"wakeup\").build());\n }\n // If we support the node name class, then add the configuration\n if (node.getCommandClass(ZWaveCommandClass.CommandClass.NODE_NAMING) != null) {\n parameters.add(\n ConfigDescriptionParameterBuilder.create(ZWaveBindingConstants.CONFIGURATION_NODENAME, Type.TEXT)\n .withLabel(\"Node Name\").withDescription(\"Sets a string for the device name\")\n .withGroupName(\"thingcfg\").withDefault(\"\").build());\n parameters.add(ConfigDescriptionParameterBuilder\n .create(ZWaveBindingConstants.CONFIGURATION_NODELOCATION, Type.TEXT)\n .withDescription(\"Sets a string for the device location\").withLabel(\"Node Location\").withDefault(\"\")\n .withGroupName(\"thingcfg\").build());\n }\n // If we support the switch_all class, then add the configuration\n if (node.getCommandClass(ZWaveCommandClass.CommandClass.SWITCH_ALL) != null) {\n List options = new ArrayList();\n options.add(new ParameterOption(\"0\", \"Exclude from All On and All Off groups\"));\n options.add(new ParameterOption(\"1\", \"Include in All On group\"));\n options.add(new ParameterOption(\"2\", \"Include in All Off group\"));\n options.add(new ParameterOption(\"255\", \"Include in All On and All Off groups\"));\n parameters.add(ConfigDescriptionParameterBuilder\n .create(ZWaveBindingConstants.CONFIGURATION_SWITCHALLMODE, Type.TEXT).withLabel(\"Switch All Mode\")\n .withDescription(\"Set the mode for the switch when receiving SWITCH ALL commands.\").withDefault(\"0\")\n .withGroupName(\"thingcfg\").withOptions(options).build());\n }\n // If we support the powerlevel class, then add the configuration\n if (node.getCommandClass(ZWaveCommandClass.CommandClass.POWERLEVEL) != null) {\n List options = new ArrayList();\n options.add(new ParameterOption(\"0\", \"Normal\"));\n options.add(new ParameterOption(\"1\", \"Minus 1dB\"));\n options.add(new ParameterOption(\"2\", \"Minus 2dB\"));\n options.add(new ParameterOption(\"3\", \"Minus 3dB\"));\n options.add(new ParameterOption(\"4\", \"Minus 4dB\"));\n options.add(new ParameterOption(\"5\", \"Minus 5dB\"));\n options.add(new ParameterOption(\"6\", \"Minus 6dB\"));\n options.add(new ParameterOption(\"7\", \"Minus 7dB\"));\n options.add(new ParameterOption(\"8\", \"Minus 8dB\"));\n options.add(new ParameterOption(\"9\", \"Minus 9dB\"));\n parameters.add(ConfigDescriptionParameterBuilder\n .create(ZWaveBindingConstants.CONFIGURATION_POWERLEVEL_LEVEL, Type.INTEGER).withLabel(\"Power Level\")\n .withDescription(\n \"Set the RF output level - Normal is maximum power
Setting the power to a lower level may be useful to reduce overloading of the receiver in adjacent nodes where they are close together, or if maximum power is not required for battery devices, it may extend battery life by reducing the transmit power.\")\n .withDefault(\"0\").withGroupName(\"thingcfg\").withOptions(options).build());\n parameters.add(ConfigDescriptionParameterBuilder\n .create(ZWaveBindingConstants.CONFIGURATION_POWERLEVEL_TIMEOUT, Type.INTEGER)\n .withLabel(\"Power Level Timeout\")\n .withDescription(\n \"Set the power level timeout in seconds
The node will reset to the normal power level if communications is not made within the specified number of seconds.\")\n .withDefault(\"0\").withGroupName(\"thingcfg\").withOptions(options).build());\n }\n // If we support DOOR_LOCK - add options\n if (node.getCommandClass(ZWaveCommandClass.CommandClass.DOOR_LOCK) != null) {\n parameters.add(ConfigDescriptionParameterBuilder\n .create(ZWaveBindingConstants.CONFIGURATION_DOORLOCKTIMEOUT, Type.TEXT).withLabel(\"Lock Timeout\")\n .withDescription(\"Set the timeout on the lock.\").withDefault(\"30\").withGroupName(\"thingcfg\")\n .build());\n }\n ZWaveUserCodeCommandClass userCodeClass = (ZWaveUserCodeCommandClass) node\n .getCommandClass(ZWaveCommandClass.CommandClass.USER_CODE);\n if (userCodeClass != null && userCodeClass.getNumberOfSupportedCodes() > 0) {\n groups.add(new ConfigDescriptionParameterGroup(\"usercode\", \"lock\", false, \"User Code\", null));\n for (int code = 1; code <= userCodeClass.getNumberOfSupportedCodes(); code++) {\n parameters.add(ConfigDescriptionParameterBuilder\n .create(ZWaveBindingConstants.CONFIGURATION_USERCODE + code, Type.TEXT)\n .withLabel(\"Code \" + code).withDescription(\"Set the user code (4 to 10 numbers)\")\n .withDefault(\"\").withGroupName(\"usercode\").build());\n }\n }\n List options = new ArrayList();\n options.add(new ParameterOption(ZWaveBindingConstants.ACTION_CHECK_VALUE.toString(), \"Do\"));\n // If we're FAILED, allow removing from the controller\n // if (node.getNodeState() == ZWaveNodeState.FAILED) {\n parameters.add(ConfigDescriptionParameterBuilder.create(\"action_remove\", Type.INTEGER)\n .withLabel(\"Remove device from controller\").withAdvanced(true).withOptions(options)\n .withDefault(\"-232323\").withGroupName(\"actions\").build());\n // } else {\n // Otherwise, allow us to put this on the failed list\n parameters.add(ConfigDescriptionParameterBuilder.create(\"action_failed\", Type.INTEGER)\n .withLabel(\"Set device as FAILed\").withAdvanced(true).withOptions(options).withDefault(\"-232323\")\n .withGroupName(\"actions\").build());\n if (node.isInitializationComplete() == true) {\n parameters.add(ConfigDescriptionParameterBuilder.create(\"action_reinit\", Type.INTEGER)\n .withLabel(\"Reinitialise the device\").withAdvanced(true).withOptions(options).withDefault(\"-232323\")\n .withGroupName(\"actions\").build());\n }\n parameters.add(ConfigDescriptionParameterBuilder.create(\"action_heal\", Type.INTEGER)\n .withLabel(\"Heal the device\").withAdvanced(true).withOptions(options).withDefault(\"-232323\")\n .withGroupName(\"actions\").build());\n return new ConfigDescription(uri, parameters, groups);\n }\n private static void initialiseZWaveThings() {\n // Check that we know about the registry\n if (thingTypeRegistry == null) {\n return;\n }\n synchronized (productIndexLock) {\n zwaveThingTypeUIDList = new HashSet();\n productIndex = new ArrayList();\n // Get all the thing types\n Collection thingTypes = thingTypeRegistry.getThingTypes();\n for (ThingType thingType : thingTypes) {\n // Is this for our binding?\n if (ZWaveBindingConstants.BINDING_ID.equals(thingType.getBindingId()) == false) {\n continue;\n }\n // Create a list of all things supported by this binding\n zwaveThingTypeUIDList.add(thingType.getUID());\n // Get the properties\n Map thingProperties = thingType.getProperties();\n if (thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_REFERENCES) == null) {\n continue;\n }\n String[] references = thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_REFERENCES).split(\",\");\n for (String ref : references) {\n String[] values = ref.split(\":\");\n Integer type;\n Integer id = null;\n if (values.length != 2) {\n continue;\n }\n type = Integer.parseInt(values[0], 16);\n if (!values[1].trim().equals(\"*\")) {\n id = Integer.parseInt(values[1], 16);\n }\n String versionMin = thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_VERSIONMIN);\n String versionMax = thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_VERSIONMAX);\n productIndex.add(new ZWaveProduct(thingType.getUID(),\n Integer.parseInt(thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_MANUFACTURER), 16),\n type, id, versionMin, versionMax));\n }\n }\n }\n }\n public static synchronized List getProductIndex() {\n // if (productIndex.size() == 0) {\n initialiseZWaveThings();\n return productIndex;\n }\n public static Set getSupportedThingTypes() {\n // if (zwaveThingTypeUIDList.size() == 0) {\n initialiseZWaveThings();\n return zwaveThingTypeUIDList;\n }\n public static ThingType getThingType(ThingTypeUID thingTypeUID) {\n // Check that we know about the registry\n if (thingTypeRegistry == null) {\n return null;\n }\n return thingTypeRegistry.getThingType(thingTypeUID);\n }\n public static ThingType getThingType(ZWaveNode node) {\n // Check that we know about the registry\n if (thingTypeRegistry == null) {\n return null;\n }\n for (ZWaveProduct product : ZWaveConfigProvider.getProductIndex()) {\n if (product.match(node) == true) {\n return thingTypeRegistry.getThingType(product.thingTypeUID);\n }\n }\n return null;\n }\n public static ConfigDescription getThingTypeConfig(ThingType type) {\n // Check that we know about the registry\n if (configDescriptionRegistry == null) {\n return null;\n }\n return configDescriptionRegistry.getConfigDescription(type.getConfigDescriptionURI());\n }\n public static Thing getThing(ThingUID thingUID) {\n // Check that we know about the registry\n if (thingRegistry == null) {\n return null;\n }\n return thingRegistry.get(thingUID);\n }\n /**\n * Check if this node supports a controllable command class\n *\n * @param node the {@link ZWaveNode)\n * @return true if a controllable class is supported\n */\n private boolean supportsControllableClass(ZWaveNode node) {\n for (CommandClass commandClass : controllableClasses) {\n if (node.supportsCommandClass(commandClass) == true) {\n return true;\n }\n }\n return false;\n }\n @Override\n public Collection getParameterOptions(URI uri, String param, Locale locale) {\n // We need to update the options of all requests for association groups...\n if (!\"thing\".equals(uri.getScheme())) {\n return null;\n }\n ThingUID thingUID = new ThingUID(uri.getSchemeSpecificPart());\n ThingType thingType = thingTypeRegistry.getThingType(thingUID.getThingTypeUID());\n if (thingType == null) {\n return null;\n }\n // Is this a zwave thing?\n if (!thingUID.getBindingId().equals(ZWaveBindingConstants.BINDING_ID)) {\n return null;\n }\n // And is it an association group?\n if (!param.startsWith(\"group_\")) {\n return null;\n }\n // And make sure this is a node because we want to get the id off the end...\n if (!thingUID.getId().startsWith(\"node\")) {\n return null;\n }\n int nodeId = Integer.parseInt(thingUID.getId().substring(4));\n Thing thing = getThing(thingUID);\n ThingUID bridgeUID = thing.getBridgeUID();\n // Get the controller for this thing\n Thing bridge = getThing(bridgeUID);\n if (bridge == null) {\n return null;\n }\n // Get its handler\n ZWaveControllerHandler handler = (ZWaveControllerHandler) bridge.getHandler();\n boolean supportsMultiInstanceAssociation = false;\n ZWaveNode myNode = handler.getNode(nodeId);\n if (myNode.getCommandClass(CommandClass.MULTI_INSTANCE_ASSOCIATION) != null) {\n supportsMultiInstanceAssociation = true;\n }\n List options = new ArrayList();\n // Add the controller (ie openHAB) to the top of the list\n options.add(new ParameterOption(\"node_\" + handler.getOwnNodeId() + \"_0\", \"openHAB Controller\"));\n // And iterate over all its nodes\n Collection nodes = handler.getNodes();\n for (ZWaveNode node : nodes) {\n // Don't add its own id or the controller\n if (node.getNodeId() == nodeId || node.getNodeId() == handler.getOwnNodeId()) {\n continue;\n }\n // Get this nodes thing so we can find the name\n // TODO: Add this when thing names are supported!\n // Thing thingNode = getThing(thingUID);\n // Add the node for the standard association class if it supports a controllable class\n if (supportsControllableClass(node)) {\n // TODO: Use the node name\n options.add(new ParameterOption(\"node_\" + node.getNodeId() + \"_0\", \"Node \" + node.getNodeId()));\n }\n // If the device supports multi_instance_association class, then add all controllable endpoints as well...\n // If this node also supports multi_instance class\n if (supportsMultiInstanceAssociation == true && node.getCommandClass(CommandClass.MULTI_INSTANCE) != null) {\n // Loop through all the endpoints for this device and add any that are controllable\n // for(node.get)\n // options.add(new ParameterOption(\"node\" + node.getNodeId() + \".\" + endpointId, \"Node \" +\n // node.getNodeId()));\n }\n }\n return Collections.unmodifiableList(options);\n }\n}"}}},{"rowIdx":1255,"cells":{"answer":{"kind":"string","value":"package au.com.museumvictoria.fieldguide.vic.fork.ui.fragments;\nimport android.app.Activity;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.Fragment;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.AdapterView;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.Toast;\nimport au.com.museumvictoria.fieldguide.vic.fork.R;\nimport au.com.museumvictoria.fieldguide.vic.fork.adapter.SpeciesListCursorAdapter;\nimport au.com.museumvictoria.fieldguide.vic.fork.db.FieldGuideDatabase;\n/**\n * A list of species in a group. This fragment also supports\n * tablet devices by allowing list items to be given an 'activated' state upon\n * selection. This helps indicate which item is currently being viewed in a\n * {@link SpeciesItemDetailFragment}.\n *\n *

Activities containing this fragment MUST implement the {@link Callbacks}\n * interface.\n */\npublic class GroupFragment extends Fragment {\n private static final String TAG = GroupFragment.class.getSimpleName();\n private static final String ARGUMENT_GROUP_NAME = \"speciesgroup\";\n /**\n * Callback interface to be notified when a species is selected. Activities using this fragment\n * must implement this interface.\n */\n public interface Callback {\n void onSpeciesSelected(String speciesId, String name, @Nullable String subname);\n }\n private Callback callback;\n private SimpleAdapter sa;\n private ListView mListView;\n private Cursor mCursor;\n private FieldGuideDatabase fgdb;\n /**\n * TODO: Document exactly what groupName we expect.\n */\n public static GroupFragment newInstance(String groupName) {\n Bundle arguments = new Bundle();\n arguments.putString(ARGUMENT_GROUP_NAME, groupName);\n GroupFragment fragment = new GroupFragment();\n fragment.setArguments(arguments);\n return fragment;\n }\n @Override\n public void onAttach(Activity activity) {\n super.onAttach(activity);\n try {\n callback = (Callback) activity;\n } catch (ClassCastException e) {\n throw new RuntimeException(\"Container activity does not implement callback.\");\n }\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n return inflater.inflate(R.layout.fragment_group, container, false);\n }\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n fgdb = FieldGuideDatabase.getInstance(getActivity()\n .getApplicationContext());\n mCursor = fgdb.getSpeciesInGroup(getArguments().getString(ARGUMENT_GROUP_NAME),\n SpeciesListCursorAdapter.getRequiredColumns());\n mListView = (ListView) getView().findViewById(R.id.species_list);\n mListView.setFastScrollEnabled(true);\n final SpeciesListCursorAdapter adapter =\n new SpeciesListCursorAdapter(getActivity().getApplicationContext(), mCursor, 0);\n mListView.setAdapter(adapter);\n mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n Log.i(TAG, \"Click\" + position + \" \" + id);\n // TODO: Need a better way to get IDs.\n callback.onSpeciesSelected(Long.toString(id), adapter.getLabelAtPosition(position),\n adapter.getSublabelAtPosition(position));\n }\n });\n }\n @Override\n public void onDestroy() {\n mCursor.close();\n super.onDestroy();\n }\n @Override\n public void onDetach() {\n callback = null;\n super.onDetach();\n }\n}"}}},{"rowIdx":1256,"cells":{"answer":{"kind":"string","value":"package com.github.kaiwinter.androidremotenotifications.model;\nimport com.github.kaiwinter.androidremotenotifications.RemoteNotifications;\nimport java.util.Date;\n/**\n * Defines how often the notifications are updated from the server. Doing this on each start of your app ({@link #NOW})\n * might lead to too many server calls. You can reduce them by using {@link #WEEKLY} or {@link #MONTHLY}.\n */\npublic enum UpdatePolicy {\n /**\n * The update is made now, regardless when the last one was.\n */\n NOW(0),\n /**\n * The update is made once a week. {@link RemoteNotifications} uses an internal shared preference to track when the last update\n * was.\n */\n WEEKLY(7 * 24 * 60 * 60 * 1000),\n /**\n * The update is made every second week. {@link RemoteNotifications} uses an internal shared preference to track when the last update\n * was.\n */\n BI_WEEKLY(WEEKLY.getInterval() * 2),\n /**\n * The update is made once a month. {@link RemoteNotifications} uses an internal shared preference to track when the last\n * update was.\n */\n MONTHLY(WEEKLY.getInterval() * 4);\n private final long interval;\n UpdatePolicy(long interval) {\n this.interval = interval;\n }\n private long getInterval() {\n return interval;\n }\n /**\n * Checks if the interval of this {@link UpdatePolicy} is over in regard to the lastUpdate.\n *\n * @param lastUpdate The {@link Date} of the last update.\n * @return true if an update should be done, else false.\n */\n public boolean shouldUpdate(Date lastUpdate) {\n if (lastUpdate == null) {\n return true;\n }\n // be robust against small time differences when using NOW\n return System.currentTimeMillis() - interval >= lastUpdate.getTime();\n }\n}"}}},{"rowIdx":1257,"cells":{"answer":{"kind":"string","value":"package edu.pitt.apollo;\nimport edu.pitt.apollo.db.ApolloDatabaseKeyNotFoundException;\nimport edu.pitt.apollo.db.ApolloDbUtils;\nimport edu.pitt.apollo.service.translatorservice.v2_0_1.TranslatorServiceEI;\nimport edu.pitt.apollo.types.v2_0_1.MethodCallStatusEnum;\nimport edu.pitt.apollo.types.v2_0_1.RunAndSoftwareIdentification;\nimport edu.pitt.apollo.types.v2_0_1.RunSimulationMessage;\nimport edu.pitt.apollo.types.v2_0_1.ServiceRegistrationRecord;\nimport edu.pitt.apollo.types.v2_0_1.SoftwareIdentification;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.sql.SQLException;\nimport java.util.Map;\nimport org.apache.cxf.endpoint.Client;\nimport org.apache.cxf.frontend.ClientProxy;\nimport org.apache.cxf.transport.http.HTTPConduit;\nimport org.apache.cxf.transports.http.configuration.HTTPClientPolicy;\nimport edu.pitt.apollo.service.simulatorservice.v2_0_1.SimulatorServiceEI;\nimport java.math.BigInteger;\npublic class ApolloRunSimulationThread extends Thread {\n private ApolloDbUtils dbUtils;\n private RunSimulationMessage message;\n private int runId;\n private static ServiceRegistrationRecord translatorServiceRecord;\n private ApolloServiceImpl apolloServiceImpl;\n public ApolloRunSimulationThread(int runId, RunSimulationMessage message, ApolloDbUtils dbUtils,\n ApolloServiceImpl apolloServiceImpl) {\n System.out.println(\"in constructor\");\n this.message = message;\n this.runId = runId;\n this.dbUtils = dbUtils;\n this.apolloServiceImpl = apolloServiceImpl;\n }\n @Override\n public void run() {\n try {\n // first call the translator and translate the runSimulationMessage\n TranslatorServiceEI translatorPort;\n try {\n translatorPort = apolloServiceImpl.getTranslatorServicePort(new URL(translatorServiceRecord.getUrl()));\n } catch (MalformedURLException ex) {\n ErrorUtils.writeErrorToFile(\"MalformedURLEXception attempting to get the translator port for runId \" + runId\n + \". URL was \" + translatorServiceRecord.getUrl() + \". Error message was: \" + ex.getMessage(),\n apolloServiceImpl.getErrorFile(runId));\n return;\n }\n // disable chunking for ZSI\n Client client = ClientProxy.getClient(translatorPort);\n HTTPConduit http = (HTTPConduit) client.getConduit();\n HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();\n httpClientPolicy.setConnectionTimeout(36000);\n httpClientPolicy.setAllowChunking(false);\n http.setClient(httpClientPolicy);\n translatorPort.translateRunSimulationMessage(Integer.toString(runId), message);\n // while translator is running, query the status\n RunAndSoftwareIdentification translatorRasid = new RunAndSoftwareIdentification();\n translatorRasid.setRunId(Integer.toString(runId));\n translatorRasid.setSoftwareId(translatorServiceRecord.getSoftwareIdentification());\n MethodCallStatusEnum status = MethodCallStatusEnum.QUEUED; // doesn't\n // really\n // matter\n try {\n while (!status.equals(MethodCallStatusEnum.TRANSLATION_COMPLETED)) {\n Thread.sleep(5000);\n status = apolloServiceImpl.getRunStatus(translatorRasid).getStatus();\n if (status.equals(MethodCallStatusEnum.FAILED)) {\n ErrorUtils.writeErrorToFile(\"Translator service returned status of FAILED for runId \" + runId,\n apolloServiceImpl.getErrorFile(runId));\n return;\n }\n }\n } catch (InterruptedException ex) {\n ErrorUtils.writeErrorToFile(\"InterruptedException while attempting to get status of translator for runId \"\n + runId + \": \" + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));\n }\n // once the translator has finished, call the simulator and start\n // the simulation\n SoftwareIdentification simulatorIdentification = message.getSimulatorIdentification();\n String url = null;\n try {\n url = dbUtils.getUrlForSoftwareIdentification(simulatorIdentification);\n SimulatorServiceEI simulatorPort = apolloServiceImpl.getSimulatorServicePort(new URL(url));\n // disable chunking for ZSI\n Client simulatorClient = ClientProxy.getClient(simulatorPort);\n HTTPConduit simulatorHttp = (HTTPConduit) simulatorClient.getConduit();\n HTTPClientPolicy simulatorHttpClientPolicy = new HTTPClientPolicy();\n simulatorHttpClientPolicy.setConnectionTimeout(36000);\n simulatorHttpClientPolicy.setAllowChunking(false);\n simulatorHttp.setClient(simulatorHttpClientPolicy);\n simulatorPort.runSimulation(new BigInteger(Integer.toString(runId)), message);\n } catch (ApolloDatabaseKeyNotFoundException ex) {\n ErrorUtils.writeErrorToFile(\n \"Apollo database key not found attempting to get URL for simulator: \"\n + simulatorIdentification.getSoftwareName() + \", version: \"\n + simulatorIdentification.getSoftwareVersion() + \", developer: \"\n + simulatorIdentification.getSoftwareDeveloper() + \" for run id \" + runId + \": \"\n + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));\n return;\n } catch (ClassNotFoundException ex) {\n ErrorUtils.writeErrorToFile(\n \"ClassNotFoundException attempting to get URL for simulator: \"\n + simulatorIdentification.getSoftwareName() + \", version: \"\n + simulatorIdentification.getSoftwareVersion() + \", developer: \"\n + simulatorIdentification.getSoftwareDeveloper() + \" for run id \" + runId + \": \"\n + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));\n return;\n } catch (MalformedURLException ex) {\n ErrorUtils.writeErrorToFile(\n \"MalformedURLException attempting to create port for simulator: \"\n + simulatorIdentification.getSoftwareName() + \", version: \"\n + simulatorIdentification.getSoftwareVersion() + \", developer: \"\n + simulatorIdentification.getSoftwareDeveloper() + \" for run id \" + runId + \". URL was: \" + url\n + \". Error message was: \" + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));\n return;\n } catch (SQLException ex) {\n ErrorUtils.writeErrorToFile(\n \"SQLException attempting to get URL for simulator: \" + simulatorIdentification.getSoftwareName()\n + \", version: \" + simulatorIdentification.getSoftwareVersion() + \", developer: \"\n + simulatorIdentification.getSoftwareDeveloper() + \" for run id \" + runId + \": \"\n + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));\n return;\n }\n try {\n dbUtils.updateLastServiceToBeCalledForRun(runId, simulatorIdentification);\n } catch (ApolloDatabaseKeyNotFoundException ex) {\n ErrorUtils.writeErrorToFile(\"Apollo database key not found attempting to update last service\"\n + \" call for run id \" + runId + \": \" + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));\n return;\n } catch (SQLException ex) {\n ErrorUtils.writeErrorToFile(\"SQLException attempting to update last service\" + \" call for run id \" + runId + \": \"\n + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));\n return;\n } catch (ClassNotFoundException ex) {\n ErrorUtils.writeErrorToFile(\"ClassNotFoundException attempting to update last service\" + \" call for run id \"\n + runId + \": \" + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));\n return;\n }\n } catch (IOException e) {\n System.out.println(\"Error writing error file!: \" + e.getMessage());\n }\n }\n public static void loadTranslatorSoftwareIdentification() {\n System.out.println(\"Loading translator software identification\");\n try {\n ApolloDbUtils dbUtils = new ApolloDbUtils(new File(ApolloServiceImpl.getDatabasePropertiesFilename()));\n Map softwareIdMap = dbUtils.getRegisteredSoftware();\n for (Integer id : softwareIdMap.keySet()) {\n SoftwareIdentification softwareId = softwareIdMap.get(id).getSoftwareIdentification();\n if (softwareId.getSoftwareName().toLowerCase().equals(\"translator\")) {\n translatorServiceRecord = softwareIdMap.get(id);\n break;\n }\n }\n } catch (ClassNotFoundException ex) {\n throw new RuntimeException(\"ClassNotFoundException attempting to load the translator service record: \"\n + ex.getMessage());\n } catch (IOException ex) {\n throw new RuntimeException(\"IOException attempting to load the translator service record: \" + ex.getMessage());\n } catch (SQLException ex) {\n throw new RuntimeException(\"SQLException attempting to load the translator service record: \" + ex.getMessage());\n }\n if (translatorServiceRecord == null) {\n throw new RuntimeException(\"Could not find translator in the list of registered services\");\n }\n }\n // static {\n // try {\n // loadTranslatorSoftwareIdentification();\n // } catch (ApolloRunSimulationException ex) {\n // throw new\n // RuntimeException(\"ApolloRunSimulationException attempting to load the translator service record: \"\n // + ex.getMessage());\n // } catch (ClassNotFoundException ex) {\n // throw new\n // RuntimeException(\"ClassNotFoundException attempting to load the translator service record: \"\n // + ex.getMessage());\n // } catch (IOException ex) {\n // throw new\n // RuntimeException(\"IOException attempting to load the translator service record: \"\n // + ex.getMessage());\n // } catch (SQLException ex) {\n // throw new\n // RuntimeException(\"SQLException attempting to load the translator service record: \"\n // + ex.getMessage());\n}"}}},{"rowIdx":1258,"cells":{"answer":{"kind":"string","value":"package com.axelor.apps.production.service.productionorder;\nimport com.axelor.apps.base.db.Product;\nimport com.axelor.apps.base.db.repo.SequenceRepository;\nimport com.axelor.apps.base.service.administration.SequenceService;\nimport com.axelor.apps.production.db.BillOfMaterial;\nimport com.axelor.apps.production.db.ManufOrder;\nimport com.axelor.apps.production.db.ProductionOrder;\nimport com.axelor.apps.production.db.repo.ProductionOrderRepository;\nimport com.axelor.apps.production.exceptions.IExceptionMessage;\nimport com.axelor.apps.production.service.manuforder.ManufOrderService;\nimport com.axelor.apps.sale.db.SaleOrder;\nimport com.axelor.exception.AxelorException;\nimport com.axelor.exception.db.repo.TraceBackRepository;\nimport com.axelor.i18n.I18n;\nimport com.google.inject.Inject;\nimport com.google.inject.persist.Transactional;\nimport java.lang.invoke.MethodHandles;\nimport java.math.BigDecimal;\nimport java.time.LocalDateTime;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\npublic class ProductionOrderServiceImpl implements ProductionOrderService {\n private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());\n protected ManufOrderService manufOrderService;\n protected SequenceService sequenceService;\n protected ProductionOrderRepository productionOrderRepo;\n @Inject\n public ProductionOrderServiceImpl(\n ManufOrderService manufOrderService,\n SequenceService sequenceService,\n ProductionOrderRepository productionOrderRepo) {\n this.manufOrderService = manufOrderService;\n this.sequenceService = sequenceService;\n this.productionOrderRepo = productionOrderRepo;\n }\n public ProductionOrder createProductionOrder(SaleOrder saleOrder) throws AxelorException {\n ProductionOrder productionOrder = new ProductionOrder(this.getProductionOrderSeq());\n if (saleOrder != null) {\n productionOrder.setClientPartner(saleOrder.getClientPartner());\n productionOrder.setSaleOrder(saleOrder);\n }\n return productionOrder;\n }\n public String getProductionOrderSeq() throws AxelorException {\n String seq = sequenceService.getSequenceNumber(SequenceRepository.PRODUCTION_ORDER);\n if (seq == null) {\n throw new AxelorException(\n TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,\n I18n.get(IExceptionMessage.PRODUCTION_ORDER_SEQ));\n }\n return seq;\n }\n /**\n * Generate a Production Order\n *\n * @param product Product must be passed in param because product can be different of bill of\n * material product (Product variant)\n * @param billOfMaterial\n * @param qtyRequested\n * @param businessProject\n * @return\n * @throws AxelorException\n */\n @Transactional(rollbackOn = {Exception.class})\n public ProductionOrder generateProductionOrder(\n Product product,\n BillOfMaterial billOfMaterial,\n BigDecimal qtyRequested,\n LocalDateTime startDate)\n throws AxelorException {\n ProductionOrder productionOrder = this.createProductionOrder(null);\n this.addManufOrder(\n productionOrder,\n product,\n billOfMaterial,\n qtyRequested,\n startDate,\n null,\n null,\n ManufOrderService.ORIGIN_TYPE_OTHER);\n return productionOrderRepo.save(productionOrder);\n }\n @Override\n @Transactional(rollbackOn = {Exception.class})\n public ProductionOrder addManufOrder(\n ProductionOrder productionOrder,\n Product product,\n BillOfMaterial billOfMaterial,\n BigDecimal qtyRequested,\n LocalDateTime startDate,\n LocalDateTime endDate,\n SaleOrder saleOrder,\n int originType)\n throws AxelorException {\n ManufOrder manufOrder =\n manufOrderService.generateManufOrder(\n product,\n qtyRequested,\n ManufOrderService.DEFAULT_PRIORITY,\n ManufOrderService.IS_TO_INVOICE,\n billOfMaterial,\n startDate,\n endDate,\n originType);\n if (manufOrder != null) {\n if (saleOrder != null) {\n manufOrder.addSaleOrderSetItem(saleOrder);\n manufOrder.setClientPartner(saleOrder.getClientPartner());\n manufOrder.setMoCommentFromSaleOrder(saleOrder.getProductionNote());\n }\n productionOrder.addManufOrderSetItem(manufOrder);\n manufOrder.addProductionOrderSetItem(productionOrder);\n }\n return productionOrderRepo.save(productionOrder);\n }\n}"}}},{"rowIdx":1259,"cells":{"answer":{"kind":"string","value":"package com.grayben.riskExtractor.htmlScorer;\nimport com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;\nimport org.jsoup.nodes.Element;\nimport org.jsoup.nodes.Node;\nimport org.jsoup.select.NodeVisitor;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\npublic class ScoringAndFlatteningNodeVisitor implements NodeVisitor {\n private Set> elementScorers;\n private ScoredText flatText;\n public ScoredText getFlatText() {\n return flatText;\n }\n private Map currentScores;\n public Map getCurrentScores(){\n return Collections.unmodifiableMap(currentScores);\n }\n private String currentString;\n private enum Operation {\n INCREMENT,\n DECREMENT\n }\n public ScoringAndFlatteningNodeVisitor(Set> elementScorers) {\n super();\n this.elementScorers = elementScorers;\n this.flatText = new ScoredText();\n this.currentScores = new HashMap<>();\n //initialise currentScores to DEFAULT_SCORE (probably 0)\n for (Scorer scorer: this.elementScorers){\n currentScores.put(scorer.getScoreLabel(), scorer.DEFAULT_SCORE);\n }\n }\n @Override\n public void head(Node node, int depth) {\n validateInput(node, depth);\n if(! isElement(node))\n return;\n Element element = (Element) node;\n processElement(element, Operation.INCREMENT);\n }\n @Override\n public void tail(Node node, int depth) {\n validateInput(node, depth);\n if (! isElement(node))\n return;\n Element element = (Element) node;\n processElement(element, Operation.DECREMENT);\n }\n private void validateInput(Node node, int depth){\n if (node == null)\n throw new NullPointerException(\n \"Node was null\"\n );\n if (depth < 0)\n throw new IllegalArgumentException(\n \"Depth was less than 0\"\n );\n }\n private boolean isElement(Node node){\n if (node.getClass().equals(Element.class))\n return true;\n else\n return false;\n }\n private void processElement(Element element, Operation operation){\n this.currentString = element.ownText();\n updateScores(element, operation);\n addScoredTextEntry();\n }\n private void updateScores(Element element, Operation operation){\n for (Scorer scorer :\n elementScorers) {\n assert this.currentScores.containsKey(scorer.getScoreLabel());\n int currentScore = this.currentScores.get(scorer.getScoreLabel());\n int elementScore = scorer.score(element);\n int newScore;\n switch (operation){\n case INCREMENT:\n newScore = currentScore + elementScore;\n break;\n case DECREMENT:\n newScore = currentScore - elementScore;\n break;\n default:\n throw new IllegalArgumentException(\n \"The operation specified is not supported\"\n );\n }\n this.currentScores.put(scorer.getScoreLabel(), newScore);\n }\n }\n private void addScoredTextEntry() {\n ScoredTextElement textElement = new ScoredTextElement(\n this.currentString, this.currentScores\n );\n this.flatText.add(textElement);\n }\n}"}}},{"rowIdx":1260,"cells":{"answer":{"kind":"string","value":"package org.openhealthtools.mdht.uml.cda.core.util;\nimport java.io.PrintStream;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.apache.commons.lang.StringUtils;\nimport org.eclipse.core.resources.IFolder;\nimport org.eclipse.core.resources.IProject;\nimport org.eclipse.core.resources.IResource;\nimport org.eclipse.core.resources.IResourceVisitor;\nimport org.eclipse.core.resources.IWorkspace;\nimport org.eclipse.core.runtime.CoreException;\nimport org.eclipse.core.runtime.IExtension;\nimport org.eclipse.core.runtime.IExtensionPoint;\nimport org.eclipse.core.runtime.IExtensionRegistry;\nimport org.eclipse.core.runtime.IPath;\nimport org.eclipse.core.runtime.Path;\nimport org.eclipse.core.runtime.Platform;\nimport org.eclipse.emf.common.util.EList;\nimport org.eclipse.emf.common.util.Enumerator;\nimport org.eclipse.emf.common.util.TreeIterator;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.util.EcoreUtil;\nimport org.eclipse.uml2.common.util.UML2Util;\nimport org.eclipse.uml2.uml.Association;\nimport org.eclipse.uml2.uml.Class;\nimport org.eclipse.uml2.uml.Classifier;\nimport org.eclipse.uml2.uml.Comment;\nimport org.eclipse.uml2.uml.Constraint;\nimport org.eclipse.uml2.uml.Element;\nimport org.eclipse.uml2.uml.Enumeration;\nimport org.eclipse.uml2.uml.EnumerationLiteral;\nimport org.eclipse.uml2.uml.Generalization;\nimport org.eclipse.uml2.uml.NamedElement;\nimport org.eclipse.uml2.uml.OpaqueExpression;\nimport org.eclipse.uml2.uml.Package;\nimport org.eclipse.uml2.uml.Property;\nimport org.eclipse.uml2.uml.Stereotype;\nimport org.eclipse.uml2.uml.Type;\nimport org.eclipse.uml2.uml.ValueSpecification;\nimport org.eclipse.uml2.uml.util.UMLSwitch;\nimport org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationship;\nimport org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationshipKind;\nimport org.openhealthtools.mdht.uml.cda.core.profile.Inline;\nimport org.openhealthtools.mdht.uml.cda.core.profile.LogicalConstraint;\nimport org.openhealthtools.mdht.uml.cda.core.profile.LogicalOperator;\nimport org.openhealthtools.mdht.uml.cda.core.profile.SeverityKind;\nimport org.openhealthtools.mdht.uml.cda.core.profile.Validation;\nimport org.openhealthtools.mdht.uml.common.util.NamedElementUtil;\nimport org.openhealthtools.mdht.uml.common.util.PropertyList;\nimport org.openhealthtools.mdht.uml.common.util.UMLUtil;\nimport org.openhealthtools.mdht.uml.term.core.profile.BindingKind;\nimport org.openhealthtools.mdht.uml.term.core.profile.CodeSystemConstraint;\nimport org.openhealthtools.mdht.uml.term.core.profile.CodeSystemVersion;\nimport org.openhealthtools.mdht.uml.term.core.profile.ValueSetConstraint;\nimport org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion;\nimport org.openhealthtools.mdht.uml.term.core.util.ITermProfileConstants;\nimport org.openhealthtools.mdht.uml.term.core.util.TermProfileUtil;\npublic class CDAModelUtil {\n public static final String CDA_PACKAGE_NAME = \"cda\";\n public static final String DATATYPES_NS_URI = \"http:\n /** This base URL may be set from preferences or Ant task options. */\n public static String INFOCENTER_URL = \"http:\n public static final String SEVERITY_ERROR = \"ERROR\";\n public static final String SEVERITY_WARNING = \"WARNING\";\n public static final String SEVERITY_INFO = \"INFO\";\n private static final String EPACKAGE = \"Ecore::EPackage\";\n private static final String EREFERENCE = \"Ecore::EReference\";\n public static final String XMLNAMESPACE = \"xmlNamespace\";\n private static final String NSPREFIX = \"nsPrefix\";\n private static final String NSURI = \"nsURI\";\n // This message may change in the future to specify certain nullFlavor Types (such as the implementation, NI)\n private static final String NULLFLAVOR_SECTION_MESSAGE = \"If section/@nullFlavor is not present, \";\n public static boolean cardinalityAfterElement = false;\n public static boolean disablePdfGeneration = false;\n public static boolean isAppendConformanceRules = false;\n public static Class getCDAClass(Classifier templateClass) {\n Class cdaClass = null;\n // if the provided class is from CDA and not a template\n if (isCDAModel(templateClass) && templateClass instanceof Class) {\n return (Class) templateClass;\n }\n for (Classifier parent : templateClass.allParents()) {\n // nearest package may be null if CDA model is not available\n if (parent.getNearestPackage() != null) {\n if (isCDAModel(parent) && parent instanceof Class) {\n cdaClass = (Class) parent;\n break;\n }\n }\n }\n return cdaClass;\n }\n public static Property getCDAProperty(Property templateProperty) {\n if (templateProperty.getClass_() == null) {\n return null;\n }\n // if the provided property is from a CDA class/datatype and not a template\n if (isCDAModel(templateProperty) || isDatatypeModel(templateProperty)) {\n return templateProperty;\n }\n for (Classifier parent : templateProperty.getClass_().allParents()) {\n for (Property inherited : parent.getAttributes()) {\n if (inherited.getName() != null && inherited.getName().equals(templateProperty.getName()) &&\n (isCDAModel(inherited) || isDatatypeModel(inherited))) {\n return inherited;\n }\n }\n }\n return null;\n }\n /**\n * Returns the nearest inherited property with the same name, or null if not found.\n *\n * @deprecated Use the {@link UMLUtil#getInheritedProperty(Property)} API, instead.\n */\n @Deprecated\n public static Property getInheritedProperty(Property templateProperty) {\n // for CDA, we restrict to Classes, not other classifiers\n if (templateProperty.getClass_() == null) {\n return null;\n }\n return UMLUtil.getInheritedProperty(templateProperty);\n }\n public static boolean isDatatypeModel(Element element) {\n if (element != null && element.getNearestPackage() != null) {\n Stereotype ePackage = element.getNearestPackage().getAppliedStereotype(\"Ecore::EPackage\");\n if (ePackage != null) {\n return DATATYPES_NS_URI.equals(element.getNearestPackage().getValue(ePackage, \"nsURI\"));\n }\n }\n return false;\n }\n /**\n * isCDAModel - use get top package to support nested uml packages within CDA model\n * primarily used for extensions\n *\n */\n public static boolean isCDAModel(Element element) {\n if (element != null) {\n Package neareastPackage = element.getNearestPackage();\n if (neareastPackage != null) {\n Package topPackage = org.openhealthtools.mdht.uml.common.util.UMLUtil.getTopPackage(neareastPackage);\n return CDA_PACKAGE_NAME.equals((topPackage != null)\n ? topPackage.getName()\n : \"\");\n }\n }\n return false;\n }\n public static Class getCDADatatype(Classifier datatype) {\n Class result = null;\n // if the provided class is from CDA datatypes\n if (isDatatypeModel(datatype) && (datatype instanceof Class)) {\n result = (Class) datatype;\n } else {\n for (Classifier parent : datatype.allParents()) {\n // nearest package may be null if CDA datatypes model is not available\n if (parent.getNearestPackage() != null) {\n if (isDatatypeModel(parent) && (parent instanceof Class)) {\n result = (Class) parent;\n break;\n }\n }\n }\n }\n return result;\n }\n public static boolean isCDAType(Type templateClass, String typeName) {\n if (templateClass instanceof Class && typeName != null) {\n Class cdaClass = getCDAClass((Class) templateClass);\n if (cdaClass != null && typeName.equals(cdaClass.getName())) {\n return true;\n }\n }\n return false;\n }\n public static boolean isClinicalDocument(Type templateClass) {\n return isCDAType(templateClass, \"ClinicalDocument\");\n }\n public static boolean isSection(Type templateClass) {\n return isCDAType(templateClass, \"Section\");\n }\n public static boolean isOrganizer(Type templateClass) {\n return isCDAType(templateClass, \"Organizer\");\n }\n public static boolean isEntry(Type templateClass) {\n return isCDAType(templateClass, \"Entry\");\n }\n public static boolean isClinicalStatement(Type templateClass) {\n if (templateClass instanceof Class) {\n Class cdaClass = getCDAClass((Class) templateClass);\n String cdaName = cdaClass == null\n ? null\n : cdaClass.getName();\n if (cdaClass != null && (\"Act\".equals(cdaName) || \"Encounter\".equals(cdaName) ||\n \"Observation\".equals(cdaName) || \"ObservationMedia\".equals(cdaName) ||\n \"Organizer\".equals(cdaName) || \"Procedure\".equals(cdaName) || \"RegionOfInterest\".equals(cdaName) ||\n \"SubstanceAdministration\".equals(cdaName) || \"Supply\".equals(cdaName))) {\n return true;\n }\n }\n return false;\n }\n public static void composeAllConformanceMessages(Element element, final PrintStream stream, final boolean markup) {\n final TreeIterator iterator = EcoreUtil.getAllContents(Collections.singletonList(element));\n while (iterator != null && iterator.hasNext()) {\n EObject child = iterator.next();\n UMLSwitch umlSwitch = new UMLSwitch() {\n @Override\n public Object caseAssociation(Association association) {\n iterator.prune();\n return association;\n }\n @Override\n public Object caseClass(Class umlClass) {\n String message = computeConformanceMessage(umlClass, markup);\n stream.println(message);\n return umlClass;\n }\n @Override\n public Object caseGeneralization(Generalization generalization) {\n String message = computeConformanceMessage(generalization, markup);\n if (message.length() > 0) {\n stream.println(message);\n }\n return generalization;\n }\n @Override\n public Object caseProperty(Property property) {\n String message = computeConformanceMessage(property, markup);\n if (message.length() > 0) {\n stream.println(message);\n }\n return property;\n }\n @Override\n public Object caseConstraint(Constraint constraint) {\n String message = computeConformanceMessage(constraint, markup);\n if (message.length() > 0) {\n stream.println(message);\n }\n return constraint;\n }\n };\n umlSwitch.doSwitch(child);\n }\n }\n public static String getValidationMessage(Element element) {\n return getValidationMessage(element, ICDAProfileConstants.VALIDATION);\n }\n /**\n * Obtains the user-specified validation message recorded in the given stereotype, or else\n * {@linkplain #computeConformanceMessage(Element, boolean) computes} a suitable conformance message if none.\n *\n * @param element\n * an element on which a validation constraint stereotype is defined\n * @param validationStereotypeName\n * the stereotype name (may be the abstract {@linkplain ICDAProfileConstants#VALIDATION Validation} stereotype)\n *\n * @return the most appropriate validation/conformance message\n *\n * @see #computeConformanceMessage(Element, boolean)\n */\n public static String getValidationMessage(Element element, String validationStereotypeName) {\n String message = null;\n Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, validationStereotypeName);\n if (validationSupport != null) {\n message = (String) element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE);\n }\n if (message == null || message.length() == 0) {\n message = computeConformanceMessage(element, false);\n }\n return message;\n }\n public static String computeConformanceMessage(Element element, final boolean markup) {\n UMLSwitch umlSwitch = new UMLSwitch() {\n @Override\n public Object caseAssociation(Association association) {\n String message = null;\n Property property = getNavigableEnd(association);\n if (property != null) {\n message = computeConformanceMessage(property, false);\n }\n return message;\n }\n @Override\n public Object caseClass(Class umlClass) {\n return computeConformanceMessage(umlClass, markup);\n }\n @Override\n public Object caseGeneralization(Generalization generalization) {\n return computeConformanceMessage(generalization, markup);\n }\n @Override\n public Object caseProperty(Property property) {\n return computeConformanceMessage(property, markup);\n }\n @Override\n public Object caseConstraint(Constraint constraint) {\n return computeConformanceMessage(constraint, markup);\n }\n };\n return (String) umlSwitch.doSwitch(element);\n }\n public static String computeConformanceMessage(Class template, final boolean markup) {\n String templateId = getTemplateId(template);\n String templateVersion = getTemplateVersion(template);\n String ruleIds = getConformanceRuleIds(template);\n if (templateId == null) {\n templateId = \"\";\n }\n String templateMultiplicity = CDATemplateComputeBuilder.getMultiplicityRange(getMultiplicityRange(template));\n final String templateIdAsBusinessName = \"=\\\"\" + templateId + \"\\\"\";\n final String templateVersionAsBusinessName = \"=\\\"\" + templateVersion + \"\\\"\";\n final String multiplicityRange = templateMultiplicity.isEmpty()\n ? \"\"\n : \" [\" + templateMultiplicity + \"]\";\n CDATemplateComputeBuilder cdaTemplater = new CDATemplateComputeBuilder() {\n @Override\n public String addTemplateIdMultiplicity() {\n return multiplicityElementToggle(markup, \"templateId\", multiplicityRange, \"\");\n }\n @Override\n public String addRootMultiplicity() {\n return multiplicityElementToggle(markup, \"@root\", \" [1..1]\", templateIdAsBusinessName);\n }\n @Override\n public String addTemplateVersion() {\n return multiplicityElementToggle(markup, \"@extension\", \" [1..1]\", templateVersionAsBusinessName);\n }\n };\n return cdaTemplater.setRequireMarkup(markup).setRuleIds(ruleIds).setTemplateVersion(\n templateVersion).setMultiplicity(multiplicityRange).compute().toString();\n }\n public static String computeConformanceMessage(Generalization generalization, boolean markup) {\n return computeConformanceMessage(generalization, markup, UMLUtil.getTopPackage(generalization));\n }\n public static String computeConformanceMessage(Generalization generalization, boolean markup, Package xrefSource) {\n Class general = (Class) generalization.getGeneral();\n StringBuffer message = new StringBuffer(computeGeneralizationConformanceMessage(general, markup, xrefSource));\n appendConformanceRuleIds(generalization, message, markup);\n return message.toString();\n }\n public static String computeGeneralizationConformanceMessage(Class general, boolean markup, Package xrefSource) {\n StringBuffer message = new StringBuffer();\n String prefix = !UMLUtil.isSameModel(xrefSource, general)\n ? getModelPrefix(general) + \" \"\n : \"\";\n String xref = computeXref(xrefSource, general);\n boolean showXref = markup && (xref != null);\n String format = showXref && xref.endsWith(\".html\")\n ? \"format=\\\"html\\\" \"\n : \"\";\n Class cdaGeneral = getCDAClass(general);\n if (cdaGeneral != null) {\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\"SHALL\");\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\" conform to \");\n } else {\n message.append(\"Extends \");\n }\n message.append(showXref\n ? \"\"\n : \"\");\n message.append(prefix).append(UMLUtil.splitName(general));\n message.append(showXref\n ? \"\"\n : \"\");\n String templateId = getTemplateId(general);\n String templateVersion = getTemplateVersion(general);\n if (templateId != null) {\n message.append(\" template (templateId: \");\n message.append(markup\n ? \"\"\n : \"\");\n message.append(templateId);\n // if there is an extension, add a colon followed by its value\n if (!StringUtils.isEmpty(templateVersion)) {\n message.append(\":\" + templateVersion);\n }\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\")\");\n }\n return message.toString();\n }\n private static String getBusinessName(NamedElement property) {\n String businessName = NamedElementUtil.getBusinessName(property);\n if (!property.getName().equals(businessName)) {\n return (\" (\" + businessName + \")\");\n }\n return \"\";\n }\n private static StringBuffer multiplicityElementToggle(Property property, boolean markup, String elementName) {\n StringBuffer message = new StringBuffer();\n message.append(\n multiplicityElementToggle(markup, elementName, getMultiplicityRange(property), getBusinessName(property)));\n return message;\n }\n private static String multiplicityElementToggle(boolean markup, String elementName, String multiplicityRange,\n String businessName) {\n StringBuffer message = new StringBuffer();\n if (!cardinalityAfterElement) {\n message.append(multiplicityRange);\n }\n message.append(\" \");\n message.append(markup\n ? \"\"\n : \"\");\n message.append(elementName);\n message.append(markup\n ? \"\"\n : \"\");\n message.append(businessName);\n message.append(markup\n ? \"\"\n : \"\");\n if (cardinalityAfterElement) {\n message.append(multiplicityRange);\n }\n return message.toString();\n }\n public static String computeAssociationConformanceMessage(Property property, boolean markup, Package xrefSource,\n boolean appendNestedConformanceRules) {\n Class endType = (property.getType() instanceof Class)\n ? (Class) property.getType()\n : null;\n if (!isInlineClass(endType) && getTemplateId(property.getClass_()) != null) {\n return computeTemplateAssociationConformanceMessage(\n property, markup, xrefSource, appendNestedConformanceRules);\n }\n StringBuffer message = new StringBuffer();\n Association association = property.getAssociation();\n if (!markup) {\n message.append(getPrefixedSplitName(property.getClass_())).append(\" \");\n }\n String keyword = getValidationKeywordWithPropertyRange(association, property);\n if (keyword != null) {\n message.append(markup\n ? \"\"\n : \"\");\n message.append(keyword);\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\" contain \");\n } else {\n if (property.getUpper() < 0 || property.getUpper() > 1) {\n message.append(\"contains \");\n } else {\n message.append(\"contain \");\n }\n }\n String elementName = getCDAElementName(property);\n message.append(getMultiplicityText(property));\n message.append(multiplicityElementToggle(property, markup, elementName));\n // appendSubsetsNotation(property, message, markup, xrefSource);\n if (appendNestedConformanceRules && endType != null) {\n if (markup && isInlineClass(endType) && !isPublishSeperately(endType)) {\n StringBuilder sb = new StringBuilder();\n appendConformanceRuleIds(association, message, markup);\n appendPropertyComments(sb, property, markup);\n appendConformanceRules(sb, endType, (property.getUpper() == 1\n ? \"This \"\n : \"Such \") +\n (property.getUpper() == 1\n ? elementName\n : NameUtilities.pluralize(elementName)) +\n \" \",\n markup);\n message.append(\" \" + sb + \" \");\n } else {\n message.append(\", where its type is \");\n String prefix = !UMLUtil.isSameModel(xrefSource, endType)\n ? getModelPrefix(endType) + \" \"\n : \"\";\n String xref = computeXref(xrefSource, endType);\n boolean showXref = markup && (xref != null);\n String format = showXref && xref.endsWith(\".html\")\n ? \"format=\\\"html\\\" \"\n : \"\";\n message.append(showXref\n ? \"\"\n : \"\");\n message.append(prefix).append(UMLUtil.splitName(endType));\n message.append(showXref\n ? \"\"\n : \"\");\n appendConformanceRuleIds(association, message, markup);\n }\n } else {\n appendConformanceRuleIds(association, message, markup);\n }\n return message.toString();\n }\n private static String computeTemplateAssociationConformanceMessage(Property property, boolean markup,\n Package xrefSource, boolean appendNestedConformanceRules) {\n StringBuffer message = new StringBuffer();\n Association association = property.getAssociation();\n String elementName = getCDAElementName(property);\n if (!markup) {\n message.append(getPrefixedSplitName(property.getClass_())).append(\" \");\n }\n // errata 384 message support: if the class owner is a section, and it has an association\n // to either a clinical statement or an Entry (Act, Observation, etc.), append the message\n for (Property p : association.getMemberEnds()) {\n if ((p.getName() != null && !p.getName().isEmpty()) && (p.getOwner() != null && p.getType() != null) &&\n (isSection((Class) p.getOwner()) && isClinicalStatement(p.getType()) || isEntry(p.getType()))) {\n message.append(NULLFLAVOR_SECTION_MESSAGE);\n }\n }\n String keyword = getValidationKeyword(association);\n if (keyword != null) {\n message.append(markup\n ? \"\"\n : \"\");\n message.append(keyword);\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\" contain \");\n } else {\n if (property.getUpper() < 0 || property.getUpper() > 1) {\n message.append(\"contains \");\n } else {\n message.append(\"contain \");\n }\n }\n message.append(multiplicityElementToggle(property, markup, elementName));\n appendConformanceRuleIds(association, message, markup);\n if (appendNestedConformanceRules && property.getType() instanceof Class) {\n Class inlinedClass = (Class) property.getType();\n if (markup && isInlineClass(inlinedClass)) {\n StringBuilder sb = new StringBuilder();\n appendPropertyComments(sb, property, markup);\n appendConformanceRules(sb, inlinedClass, (property.getUpper() == 1\n ? \"This \"\n : \"Such \") +\n (property.getUpper() == 1\n ? elementName\n : NameUtilities.pluralize(elementName)) +\n \" \",\n markup);\n message.append(\" \" + sb);\n }\n }\n if (!markup) {\n String assocConstraints = computeAssociationConstraints(property, markup);\n if (assocConstraints.length() > 0) {\n message.append(assocConstraints);\n }\n }\n return message.toString();\n }\n public static String computeAssociationConstraints(Property property, boolean markup) {\n StringBuffer message = new StringBuffer();\n Association association = property.getAssociation();\n Package xrefSource = UMLUtil.getTopPackage(property);\n EntryRelationship entryRelationship = CDAProfileUtil.getEntryRelationship(association);\n EntryRelationshipKind typeCode = entryRelationship != null\n ? entryRelationship.getTypeCode()\n : null;\n Class endType = (property.getType() instanceof Class)\n ? (Class) property.getType()\n : null;\n if (typeCode != null) {\n message.append(markup\n ? \"\\n
  • \"\n : \" \");\n message.append(\"Contains \");\n message.append(markup\n ? \"\"\n : \"\").append(\"@typeCode=\\\"\").append(\n markup\n ? \"\"\n : \"\");\n message.append(typeCode).append(\"\\\" \");\n message.append(markup\n ? \"\"\n : \"\");\n message.append(markup\n ? \"\"\n : \"\");\n message.append(typeCode.getLiteral());\n message.append(markup\n ? \"\"\n : \"\");\n message.append(markup\n ? \"
  • \"\n : \", and\");\n }\n // TODO: what I should really do is test for an *implied* ActRelationship or Participation association\n if (endType != null && getCDAClass(endType) != null && !(isInlineClass(endType)) &&\n !isInlineClass(property.getClass_())) {\n message.append(markup\n ? \"\\n
  • \"\n : \" \");\n message.append(\"Contains exactly one [1..1] \");\n String prefix = !UMLUtil.isSameModel(xrefSource, endType)\n ? getModelPrefix(endType) + \" \"\n : \"\";\n String xref = computeXref(xrefSource, endType);\n boolean showXref = markup && (xref != null);\n String format = showXref && xref.endsWith(\".html\")\n ? \"format=\\\"html\\\" \"\n : \"\";\n message.append(showXref\n ? \"\"\n : \"\");\n message.append(prefix).append(UMLUtil.splitName(endType));\n message.append(showXref\n ? \"\"\n : \"\");\n String templateId = getTemplateId(endType);\n String templateVersion = getTemplateVersion(endType);\n if (templateId != null) {\n message.append(\" (templateId: \");\n message.append(markup\n ? \"\"\n : \"\");\n message.append(templateId);\n // if there is an extension, add a colon followed by its value\n if (!StringUtils.isEmpty(templateVersion)) {\n message.append(\":\" + templateVersion);\n }\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\")\");\n }\n message.append(markup\n ? \"
  • \"\n : \"\");\n }\n return message.toString();\n }\n public static String computeConformanceMessage(Property property, boolean markup) {\n return computeConformanceMessage(property, markup, UMLUtil.getTopPackage(property));\n }\n private static String getNameSpacePrefix(Property property) {\n Property cdaBaseProperty = CDAModelUtil.getCDAProperty(property);\n String nameSpacePrefix = null;\n if (cdaBaseProperty != null) {\n Stereotype eReferenceStereoetype = cdaBaseProperty.getAppliedStereotype(CDAModelUtil.EREFERENCE);\n if (eReferenceStereoetype != null) {\n String nameSpace = (String) cdaBaseProperty.getValue(eReferenceStereoetype, CDAModelUtil.XMLNAMESPACE);\n if (!StringUtils.isEmpty(nameSpace)) {\n Package topPackage = org.openhealthtools.mdht.uml.common.util.UMLUtil.getTopPackage(\n cdaBaseProperty.getNearestPackage());\n Stereotype ePackageStereoetype = topPackage.getApplicableStereotype(CDAModelUtil.EPACKAGE);\n if (ePackageStereoetype != null) {\n if (nameSpace.equals(topPackage.getValue(ePackageStereoetype, CDAModelUtil.NSURI))) {\n nameSpacePrefix = (String) topPackage.getValue(ePackageStereoetype, CDAModelUtil.NSPREFIX);\n } else {\n for (Package nestedPackage : topPackage.getNestedPackages()) {\n if (nameSpace.equals(nestedPackage.getValue(ePackageStereoetype, CDAModelUtil.NSURI))) {\n nameSpacePrefix = (String) nestedPackage.getValue(\n ePackageStereoetype, CDAModelUtil.NSPREFIX);\n }\n }\n }\n }\n }\n }\n }\n return nameSpacePrefix;\n }\n public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource) {\n return computeConformanceMessage(property, markup, xrefSource, true);\n }\n public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource,\n boolean appendNestedConformanceRules) {\n if (property.getType() == null) {\n System.out.println(\"Property has null type: \" + property.getQualifiedName());\n }\n if (property.getAssociation() != null && property.isNavigable()) {\n return computeAssociationConformanceMessage(property, markup, xrefSource, appendNestedConformanceRules);\n }\n StringBuffer message = new StringBuffer();\n if (!markup) {\n message.append(getPrefixedSplitName(property.getClass_())).append(\" \");\n }\n String keyword = getValidationKeywordWithPropertyRange(property);\n if (keyword != null) {\n message.append(markup\n ? \"\"\n : \"\");\n message.append(keyword);\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\" contain \");\n } else {\n if (property.getUpper() < 0 || property.getUpper() > 1) {\n message.append(\"contains \");\n } else {\n message.append(\"contain \");\n }\n }\n message.append(getMultiplicityText(property));\n if (!cardinalityAfterElement) {\n message.append(getMultiplicityRange(property));\n }\n message.append(\" \");\n message.append(markup\n ? \"\"\n : \"\");\n // classCode/moodCode\n if (isXMLAttribute(property)) {\n message.append(\"@\");\n }\n String propertyPrefix = getNameSpacePrefix(property);\n // Try to get CDA Name\n IExtensionRegistry reg = Platform.getExtensionRegistry();\n IExtensionPoint ep = reg.getExtensionPoint(\"org.openhealthtools.mdht.uml.cda.core.TransformProvider\");\n IExtension[] extensions = ep.getExtensions();\n TransformProvider newContributor = null;\n Property cdaProperty = null;\n try {\n newContributor = (TransformProvider) extensions[0].getConfigurationElements()[0].createExecutableExtension(\n \"transform-class\");\n cdaProperty = newContributor.GetTransform(property);\n } catch (Exception e) {\n e.printStackTrace();\n }\n String propertyCdaName = null;\n if (cdaProperty != null) {\n propertyCdaName = getCDAName(cdaProperty);\n } else {\n propertyCdaName = getCDAElementName(property);\n }\n message.append(propertyPrefix != null\n ? propertyPrefix + \":\" + propertyCdaName\n : propertyCdaName);\n message.append(markup\n ? \"\"\n : \"\");\n message.append(getBusinessName(property));\n if (property.getDefault() != null) {\n message.append(\"=\\\"\").append(property.getDefault()).append(\"\\\" \");\n }\n message.append(markup\n ? \"\"\n : \"\");\n if (cardinalityAfterElement) {\n message.append(getMultiplicityRange(property));\n }\n Stereotype nullFlavorSpecification = CDAProfileUtil.getAppliedCDAStereotype(\n property, ICDAProfileConstants.NULL_FLAVOR);\n Stereotype textValue = CDAProfileUtil.getAppliedCDAStereotype(property, ICDAProfileConstants.TEXT_VALUE);\n if (nullFlavorSpecification != null) {\n String nullFlavor = getLiteralValue(\n property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR);\n Enumeration profileEnum = (Enumeration) nullFlavorSpecification.getProfile().getOwnedType(\n ICDAProfileConstants.NULL_FLAVOR_KIND);\n String nullFlavorLabel = getLiteralValueLabel(\n property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR, profileEnum);\n if (nullFlavor != null) {\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\"/@nullFlavor\");\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\" = \\\"\").append(nullFlavor).append(\"\\\" \");\n message.append(markup\n ? \"\"\n : \"\");\n message.append(nullFlavorLabel);\n message.append(markup\n ? \"\"\n : \"\");\n }\n }\n if (textValue != null) {\n String value = (String) property.getValue(textValue, ICDAProfileConstants.TEXT_VALUE_VALUE);\n if (value != null && value.length() > 0) {\n SeverityKind level = (SeverityKind) property.getValue(\n textValue, ICDAProfileConstants.VALIDATION_SEVERITY);\n message.append(\" and \").append(markup\n ? \"\"\n : \"\").append(\n level != null\n ? getValidationKeyword(level.getLiteral())\n : keyword).append(\n markup\n ? \"\"\n : \"\").append(\" equal \\\"\").append(value).append(\"\\\"\");\n }\n }\n /*\n * Append datatype restriction, if redefined to a specialized type\n */\n List redefinedProperties = UMLUtil.getRedefinedProperties(property);\n Property redefinedProperty = redefinedProperties.isEmpty()\n ? null\n : redefinedProperties.get(0);\n if (property.getType() != null && ((redefinedProperty == null ||\n (!isXMLAttribute(property) && (property.getType() != redefinedProperty.getType()))))) {\n message.append(\" with \" + \"@xsi:type=\\\"\");\n if (redefinedProperty != null && redefinedProperty.getType() != null &&\n redefinedProperty.getType().getName() != null && !redefinedProperty.getType().getName().isEmpty()) {\n message.append(redefinedProperty.getType().getName());\n } else {\n message.append(property.getType().getName());\n }\n message.append(\"\\\"\");\n }\n // for vocab properties, put rule ID at end, use terminology constraint if specified\n if (isHL7VocabAttribute(property)) {\n String ruleIds = getTerminologyConformanceRuleIds(property);\n // if there are terminology rule IDs, then include property rule IDs here\n if (ruleIds.length() > 0) {\n appendConformanceRuleIds(property, message, markup);\n }\n } else {\n // PropertyConstraint stereotype ruleIds, if specified\n appendConformanceRuleIds(property, message, markup);\n }\n Stereotype codeSystemConstraint = TermProfileUtil.getAppliedStereotype(\n property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);\n Stereotype valueSetConstraint = TermProfileUtil.getAppliedStereotype(\n property, ITermProfileConstants.VALUE_SET_CONSTRAINT);\n if (codeSystemConstraint != null) {\n String vocab = computeCodeSystemMessage(property, markup);\n message.append(vocab);\n } else if (valueSetConstraint != null) {\n String vocab = computeValueSetMessage(property, markup, xrefSource);\n message.append(vocab);\n } else if (isHL7VocabAttribute(property) && property.getDefault() != null) {\n String vocab = computeHL7VocabAttributeMessage(property, markup);\n message.append(vocab);\n }\n // for vocab properties, put rule ID at end, use terminology constraint if specified\n if (isHL7VocabAttribute(property)) {\n String ruleIds = getTerminologyConformanceRuleIds(property);\n if (ruleIds.length() > 0) {\n appendTerminologyConformanceRuleIds(property, message, markup);\n } else {\n appendConformanceRuleIds(property, message, markup);\n }\n } else {\n // rule IDs for the terminology constraint\n appendTerminologyConformanceRuleIds(property, message, markup);\n }\n if (property.getType() != null && appendNestedConformanceRules && property.getType() instanceof Class) {\n if (isInlineClass((Class) property.getType())) {\n if (isPublishSeperately((Class) property.getType())) {\n String xref = (property.getType() instanceof Classifier &&\n UMLUtil.isSameProject(property, property.getType()))\n ? computeXref(xrefSource, (Classifier) property.getType())\n : null;\n boolean showXref = markup && (xref != null);\n if (showXref) {\n String format = showXref && xref.endsWith(\".html\")\n ? \"format=\\\"html\\\" \"\n : \"\";\n message.append(showXref\n ? \"\"\n : \"\");\n message.append(UMLUtil.splitName(property.getType()));\n message.append(showXref\n ? \"\"\n : \"\");\n }\n } else {\n StringBuilder sb = new StringBuilder();\n boolean hadSideEffect = appendPropertyComments(sb, property, markup);\n if (isAppendConformanceRules) {\n int len = sb.length();\n appendConformanceRules(sb, (Class) property.getType(), \"\", markup);\n hadSideEffect |= sb.length() > len;\n }\n if (hadSideEffect) {\n message.append(\" \" + sb);\n }\n }\n }\n }\n return message.toString();\n }\n /**\n * getCDAName\n *\n * recursively, depth first, check the object graph for a CDA Name using the root of the \"redefined\"\n * property if it exists.\n *\n * Also handle special cases like sectionId which has a cdaName of ID\n *\n * @param cdaProperty\n * an MDHT property\n * @return string\n * the calculated CDA name\n */\n private static String getCDAName(Property cdaProperty) {\n EList redefines = cdaProperty.getRedefinedProperties();\n // if there is a stereotype name, use it\n String name = getStereotypeName(cdaProperty);\n if (name != null) {\n return name;\n }\n // if there are redefines, check for more but only along the first branch (0)\n if (redefines != null && redefines.size() > 0) {\n return getCDAName(redefines.get(0));\n }\n // eventually return the property Name of the root redefined element;\n return cdaProperty.getName();\n }\n /**\n * Get the CDA name from a stereotype if it exists\n *\n * @param cdaProperty\n * a Property\n * @return the xmlName or null if no stereotype exists\n */\n private static String getStereotypeName(Property cdaProperty) {\n Stereotype eAttribute = cdaProperty.getAppliedStereotype(\"Ecore::EAttribute\");\n String name = null;\n if (eAttribute != null) {\n name = (String) cdaProperty.getValue(eAttribute, \"xmlName\");\n }\n return name;\n }\n private static void appendSubsetsNotation(Property property, StringBuffer message, boolean markup,\n Package xrefSource) {\n StringBuffer notation = new StringBuffer();\n for (Property subsets : property.getSubsettedProperties()) {\n if (subsets.getClass_() == null) {\n // eliminate NPE when publishing stereotype references to UML metamodel\n continue;\n }\n if (notation.length() == 0) {\n notation.append(\" {subsets \");\n } else {\n notation.append(\", \");\n }\n String xref = computeXref(xrefSource, subsets.getClass_());\n boolean showXref = markup && (xref != null);\n String format = showXref && xref.endsWith(\".html\")\n ? \"format=\\\"html\\\" \"\n : \"\";\n notation.append(showXref\n ? \" \"\n : \" \");\n notation.append(UMLUtil.splitName(subsets.getClass_()));\n notation.append(showXref\n ? \"\"\n : \"\");\n notation.append(\"::\" + subsets.getName());\n }\n if (notation.length() > 0) {\n notation.append(\"}\");\n }\n message.append(notation);\n }\n private static final String[] OL = { \"
      \", \"
    \" };\n private static final String[] LI = { \"
  • \", \"
  • \" };\n private static final String[] NOOL = { \"\", \" \" };\n private static final String[] NOLI = { \"\", \" \" };\n static private void appendConformanceRules(StringBuilder appendB, Class umlClass, String prefix, boolean markup) {\n String[] ol = markup\n ? OL\n : NOOL;\n String[] li = markup\n ? LI\n : NOLI;\n StringBuilder sb = new StringBuilder();\n boolean hasRules = false;\n if (!CDAModelUtil.isInlineClass(umlClass)) {\n for (Generalization generalization : umlClass.getGeneralizations()) {\n Classifier general = generalization.getGeneral();\n if (!RIMModelUtil.isRIMModel(general) && !CDAModelUtil.isCDAModel(general)) {\n String message = CDAModelUtil.computeConformanceMessage(generalization, markup);\n if (message.length() > 0) {\n hasRules = true;\n sb.append(li[0] + prefix + message + li[1]);\n }\n }\n }\n }\n // categorize constraints by constrainedElement name\n List unprocessedConstraints = new ArrayList();\n // propertyName -> constraints\n Map> constraintMap = new HashMap>();\n // constraint -> sub-constraints\n Map> subConstraintMap = new HashMap>();\n for (Constraint constraint : umlClass.getOwnedRules()) {\n unprocessedConstraints.add(constraint);\n // Do not associate logical constraints with a property because they are a class and not a property constraint\n if (CDAProfileUtil.getLogicalConstraint(constraint) == null) {\n for (Element element : constraint.getConstrainedElements()) {\n if (element instanceof Property) {\n String name = ((Property) element).getName();\n List rules = constraintMap.get(name);\n if (rules == null) {\n rules = new ArrayList();\n constraintMap.put(name, rules);\n }\n rules.add(constraint);\n } else if (element instanceof Constraint) {\n Constraint subConstraint = (Constraint) element;\n List rules = subConstraintMap.get(subConstraint);\n if (rules == null) {\n rules = new ArrayList();\n subConstraintMap.put(subConstraint, rules);\n }\n rules.add(constraint);\n }\n }\n }\n }\n PropertyList propertyList = new PropertyList(umlClass, CDAModelUtil.isInlineClass(umlClass));\n // XML attributes\n for (Property property : propertyList.getAttributes()) {\n hasRules = hasRules | appendPropertyList(\n umlClass, property, markup, ol, sb, prefix, li, constraintMap, unprocessedConstraints,\n subConstraintMap);\n }\n // XML elements\n for (Property property : propertyList.getAssociationEnds()) {\n hasRules = hasRules | appendPropertyList(\n umlClass, property, markup, ol, sb, prefix, li, constraintMap, unprocessedConstraints,\n subConstraintMap);\n }\n for (Constraint constraint : unprocessedConstraints) {\n hasRules = true;\n sb.append(li[0] + prefix + CDAModelUtil.computeConformanceMessage(constraint, markup) + li[1]);\n }\n if (hasRules) {\n appendB.append(ol[0]);\n appendB.append(sb);\n appendB.append(ol[1]);\n }\n }\n private static boolean appendPropertyList(Element umlClass, Property property, boolean markup, String[] ol,\n StringBuilder sb, String prefix, String[] li, Map> constraintMap,\n List unprocessedConstraints, Map> subConstraintMap) {\n boolean result = false;\n if (!CDAModelUtil.isCDAModel(umlClass) && !CDAModelUtil.isCDAModel(property) &&\n !CDAModelUtil.isDatatypeModel(property)) {\n result = true;\n String ccm = CDAModelUtil.computeConformanceMessage(property, markup);\n boolean order = ccm.trim().endsWith(ol[1]);\n boolean currentlyItem = false;\n if (order) {\n int olIndex = ccm.lastIndexOf(ol[1]);\n ccm = ccm.substring(0, olIndex);\n currentlyItem = ccm.trim().endsWith(li[1]);\n }\n sb.append(li[0] + prefix + ccm);\n StringBuilder propertyComments = new StringBuilder();\n currentlyItem &= appendPropertyComments(propertyComments, property, markup);\n if (currentlyItem) {\n sb.append(li[0]).append(propertyComments).append(li[1]);\n }\n appendPropertyRules(sb, property, constraintMap, subConstraintMap, unprocessedConstraints, markup, !order);\n if (order) {\n sb.append(ol[1]);\n }\n sb.append(li[1]);\n }\n return result;\n }\n private static boolean appendPropertyComments(StringBuilder sb, Property property, boolean markup) {\n // INLINE\n Association association = property.getAssociation();\n int startingStrLength = sb.length();\n if (association != null && association.getOwnedComments().size() > 0) {\n if (markup) {\n sb.append(\"

    \");\n }\n for (Comment comment : association.getOwnedComments()) {\n sb.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody()));\n }\n if (markup) {\n sb.append(\"

    \");\n }\n }\n if (property.getOwnedComments().size() > 0) {\n if (markup) {\n sb.append(\"

    \");\n }\n for (Comment comment : property.getOwnedComments()) {\n sb.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody()));\n }\n if (markup) {\n sb.append(\"

    \");\n }\n }\n return sb.length() > startingStrLength;\n }\n private static void appendPropertyRules(StringBuilder sb, Property property,\n Map> constraintMap, Map> subConstraintMap,\n List unprocessedConstraints, boolean markup, boolean newOrder) {\n String[] ol = markup && newOrder\n ? OL\n : NOOL;\n String[] li = markup\n ? LI\n : NOLI;\n // association typeCode and property type\n String assocConstraints = \"\";\n if (property.getAssociation() != null) {\n assocConstraints = CDAModelUtil.computeAssociationConstraints(property, markup);\n }\n StringBuffer ruleConstraints = new StringBuffer();\n List rules = constraintMap.get(property.getName());\n if (rules != null && !rules.isEmpty()) {\n for (Constraint constraint : rules) {\n unprocessedConstraints.remove(constraint);\n ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(constraint, markup));\n appendSubConstraintRules(ruleConstraints, constraint, subConstraintMap, unprocessedConstraints, markup);\n ruleConstraints.append(li[1]);\n }\n }\n if (assocConstraints.length() > 0 || ruleConstraints.length() > 0) {\n sb.append(ol[0]);\n sb.append(assocConstraints);\n sb.append(ruleConstraints);\n sb.append(ol[1]);\n }\n }\n private static void appendSubConstraintRules(StringBuffer ruleConstraints, Constraint constraint,\n Map> subConstraintMap, List unprocessedConstraints,\n boolean markup) {\n String[] ol;\n String[] li;\n if (markup) {\n ol = OL;\n li = LI;\n } else {\n ol = NOOL;\n li = NOLI;\n }\n List subConstraints = subConstraintMap.get(constraint);\n if (subConstraints != null && subConstraints.size() > 0) {\n ruleConstraints.append(ol[0]);\n for (Constraint subConstraint : subConstraints) {\n unprocessedConstraints.remove(subConstraint);\n ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(subConstraint, markup));\n appendSubConstraintRules(\n ruleConstraints, subConstraint, subConstraintMap, unprocessedConstraints, markup);\n ruleConstraints.append(li[1]);\n }\n ruleConstraints.append(ol[1]);\n }\n }\n private static boolean isHL7VocabAttribute(Property property) {\n String name = property.getName();\n return \"classCode\".equals(name) || \"moodCode\".equals(name) || \"typeCode\".equals(name);\n }\n private static String computeHL7VocabAttributeMessage(Property property, boolean markup) {\n StringBuffer message = new StringBuffer();\n Class rimClass = RIMModelUtil.getRIMClass(property.getClass_());\n String code = property.getDefault();\n String displayName = null;\n String codeSystemId = null;\n String codeSystemName = null;\n if (rimClass != null) {\n if (\"Act\".equals(rimClass.getName())) {\n if (\"classCode\".equals(property.getName())) {\n codeSystemName = \"HL7ActClass\";\n codeSystemId = \"2.16.840.1.113883.5.6\";\n if (\"ACT\".equals(code)) {\n displayName = \"Act\";\n } else if (\"OBS\".equals(code)) {\n displayName = \"Observation\";\n }\n } else if (\"moodCode\".equals(property.getName())) {\n codeSystemName = \"HL7ActMood\";\n codeSystemId = \"2.16.840.1.113883.5.1001\";\n if (\"EVN\".equals(code)) {\n displayName = \"Event\";\n }\n }\n }\n }\n if (displayName != null) {\n message.append(markup\n ? \"\"\n : \"\");\n message.append(displayName);\n message.append(markup\n ? \"\"\n : \"\");\n }\n if (codeSystemId != null || codeSystemName != null) {\n message.append(\" (CodeSystem:\");\n message.append(markup\n ? \"\"\n : \"\");\n if (codeSystemId != null) {\n message.append(\" \").append(codeSystemId);\n }\n if (codeSystemName != null) {\n message.append(\" \").append(codeSystemName);\n }\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\")\");\n }\n return message.toString();\n }\n private static String computeCodeSystemMessage(Property property, boolean markup) {\n Stereotype codeSystemConstraintStereotype = TermProfileUtil.getAppliedStereotype(\n property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);\n CodeSystemConstraint codeSystemConstraint = TermProfileUtil.getCodeSystemConstraint(property);\n String keyword = getValidationKeyword(property, codeSystemConstraintStereotype);\n String id = null;\n String name = null;\n String code = null;\n String displayName = null;\n if (codeSystemConstraint != null) {\n if (codeSystemConstraint.getReference() != null) {\n CodeSystemVersion codeSystemVersion = codeSystemConstraint.getReference();\n id = codeSystemVersion.getIdentifier();\n name = codeSystemVersion.getEnumerationName();\n codeSystemVersion.getVersion();\n } else {\n id = codeSystemConstraint.getIdentifier();\n name = codeSystemConstraint.getName();\n codeSystemConstraint.getVersion();\n }\n codeSystemConstraint.getBinding();\n code = codeSystemConstraint.getCode();\n displayName = codeSystemConstraint.getDisplayName();\n }\n StringBuffer message = new StringBuffer();\n if (code != null) {\n message.append(markup\n ? \"\"\n : \"\");\n // single value binding\n message.append(\"/@code\");\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\"=\\\"\").append(code).append(\"\\\" \");\n message.append(markup\n ? \"\"\n : \"\");\n if (displayName != null) {\n message.append(markup\n ? \"\"\n : \"\");\n message.append(displayName);\n message.append(markup\n ? \"\"\n : \"\");\n }\n } else {\n // capture and return proper xml binding message based on mandatory or not\n message.append(mandatoryOrNotMessage(property));\n if (keyword != null) {\n message.append(markup\n ? \"\"\n : \"\");\n message.append(keyword);\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\" be\");\n } else {\n message.append(\"is\");\n }\n message.append(\" selected from\");\n }\n if (id != null || name != null) {\n message.append(\" (CodeSystem:\");\n message.append(markup\n ? \"\"\n : \"\");\n if (id != null) {\n message.append(\" \").append(id);\n }\n if (name != null) {\n message.append(\" \").append(name);\n }\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\")\");\n }\n return message.toString();\n }\n private static String computeValueSetMessage(Property property, boolean markup, Package xrefSource) {\n Stereotype valueSetConstraintStereotype = TermProfileUtil.getAppliedStereotype(\n property, ITermProfileConstants.VALUE_SET_CONSTRAINT);\n ValueSetConstraint valueSetConstraint = TermProfileUtil.getValueSetConstraint(property);\n String keyword = getValidationKeyword(property, valueSetConstraintStereotype);\n String id = null;\n String name = null;\n String version = null;\n BindingKind binding = null;\n String xref = null;\n String xrefFormat = \"\";\n boolean showXref = false;\n if (valueSetConstraint != null) {\n if (valueSetConstraint.getReference() != null) {\n ValueSetVersion valueSetVersion = valueSetConstraint.getReference();\n id = valueSetVersion.getIdentifier();\n name = valueSetVersion.getEnumerationName();\n version = valueSetVersion.getVersion();\n binding = valueSetVersion.getBinding();\n if (valueSetVersion.getBase_Enumeration() != null) {\n xref = computeTerminologyXref(property.getClass_(), valueSetVersion.getBase_Enumeration());\n }\n showXref = markup && (xref != null);\n xrefFormat = showXref && xref.endsWith(\".html\")\n ? \"format=\\\"html\\\" \"\n : \"\";\n } else {\n id = valueSetConstraint.getIdentifier();\n name = valueSetConstraint.getName();\n version = valueSetConstraint.getVersion();\n binding = valueSetConstraint.getBinding();\n }\n }\n StringBuffer message = new StringBuffer();\n // capture and return proper xml binding message based on mandatory or not\n message.append(mandatoryOrNotMessage(property));\n if (keyword != null) {\n message.append(markup\n ? \"\"\n : \"\");\n message.append(keyword);\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\" be\");\n } else {\n message.append(\"is\");\n }\n message.append(\" selected from ValueSet\");\n message.append(markup\n ? \"\"\n : \"\");\n if (name != null) {\n message.append(\" \");\n message.append(showXref\n ? \"\"\n : \"\");\n message.append(name);\n message.append(showXref\n ? \"\"\n : \"\");\n }\n if (id != null) {\n message.append(\" \").append(id);\n }\n message.append(markup\n ? \"\"\n : \"\");\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\" \").append(binding.getName().toUpperCase());\n message.append(markup\n ? \"\"\n : \"\");\n if (BindingKind.STATIC == binding && version != null) {\n message.append(\" \").append(version);\n }\n return message.toString();\n }\n public static String computeConformanceMessage(Constraint constraint, boolean markup) {\n LogicalConstraint logicConstraint = CDAProfileUtil.getLogicalConstraint(constraint);\n if (logicConstraint != null) {\n return computeLogicalConformanceMessage(constraint, logicConstraint, markup);\n } else {\n return computeCustomConformanceMessage(constraint, markup);\n }\n }\n private static String computeCustomConformanceMessage(Constraint constraint, boolean markup) {\n StringBuffer message = new StringBuffer();\n String strucTextBody = null;\n String analysisBody = null;\n Map langBodyMap = new HashMap();\n CDAProfileUtil.getLogicalConstraint(constraint);\n ValueSpecification spec = constraint.getSpecification();\n if (spec instanceof OpaqueExpression) {\n for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) {\n String lang = ((OpaqueExpression) spec).getLanguages().get(i);\n String body = ((OpaqueExpression) spec).getBodies().get(i);\n if (\"StrucText\".equals(lang)) {\n strucTextBody = body;\n } else if (\"Analysis\".equals(lang)) {\n analysisBody = body;\n } else {\n langBodyMap.put(lang, body);\n }\n }\n }\n String displayBody = null;\n if (strucTextBody != null && strucTextBody.trim().length() > 0) {\n // TODO if markup, parse strucTextBody and insert DITA markup\n displayBody = strucTextBody;\n } else if (analysisBody != null && analysisBody.trim().length() > 0) {\n Boolean ditaEnabled = false;\n try {\n Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(\n constraint, ICDAProfileConstants.CONSTRAINT_VALIDATION);\n ditaEnabled = (Boolean) constraint.getValue(stereotype, ICDAProfileConstants.CONSTRAINT_DITA_ENABLED);\n } catch (IllegalArgumentException e) { /* Swallow this */\n }\n if (markup && !ditaEnabled) {\n // escape non-dita markup in analysis text\n displayBody = escapeMarkupCharacters(analysisBody);\n // change severity words to bold text\n displayBody = replaceSeverityWithBold(displayBody);\n } else {\n displayBody = analysisBody;\n }\n }\n if (displayBody == null) {\n List stereotypes = constraint.getAppliedStereotypes();\n if (stereotypes.isEmpty()) {\n // This should never happen but in case it does we deal with it appropriately\n // by bypassing custom constraint message additions\n return \"\";\n }\n }\n if (!markup) {\n message.append(getPrefixedSplitName(constraint.getContext())).append(\" \");\n }\n if (displayBody == null || !containsSeverityWord(displayBody)) {\n String keyword = getValidationKeyword(constraint);\n if (keyword == null) {\n keyword = \"SHALL\";\n }\n message.append(markup\n ? \"\"\n : \"\");\n message.append(keyword);\n message.append(markup\n ? \"\"\n : \"\");\n message.append(\" satisfy: \");\n }\n if (displayBody == null) {\n message.append(constraint.getName());\n } else {\n message.append(displayBody);\n }\n appendConformanceRuleIds(constraint, message, markup);\n if (!markup) {\n // remove line feeds\n int index;\n while ((index = message.indexOf(\"\\r\")) >= 0) {\n message.deleteCharAt(index);\n }\n while ((index = message.indexOf(\"\\n\")) >= 0) {\n message.deleteCharAt(index);\n if (message.charAt(index) != ' ') {\n message.insert(index, \" \");\n }\n }\n }\n return message.toString();\n }\n private static String computeLogicalConformanceMessage(Constraint constraint, LogicalConstraint logicConstraint,\n boolean markup) {\n StringBuffer message = new StringBuffer();\n logicConstraint.getMessage();\n String keyword = getValidationKeyword(constraint);\n if (keyword == null) {\n keyword = \"SHALL\";\n }\n // Wording for IFTHEN - IF xxx then SHALL yyy\n if (!logicConstraint.getOperation().equals(LogicalOperator.IFTHEN)) {\n message.append(markup\n ? \"\"\n : \"\");\n message.append(keyword);\n message.append(markup\n ? \"\"\n : \"\");\n }\n switch (logicConstraint.getOperation()) {\n case XOR:\n message.append(\" contain one and only one of the following \");\n break;\n case AND:\n message.append(\" contain all of the following \");\n break;\n case OR:\n message.append(\" contain one or more of the following \");\n case IFTHEN:\n message.append(\"if \");\n break;\n case NOTBOTH:\n message.append(\" contain zero or one of the following but not both \");\n break;\n default:\n message.append(\" satisfy the following \");\n break;\n }\n if (logicConstraint.getOperation().equals(LogicalOperator.IFTHEN) &&\n constraint.getConstrainedElements().size() == 2) {\n String propertyKeyword = getValidationKeyword(constraint.getConstrainedElements().get(0));\n if (propertyKeyword != null) {\n message.append(\n computeConformanceMessage(constraint.getConstrainedElements().get(0), markup).replace(\n propertyKeyword, \"\"));\n } else {\n message.append(computeConformanceMessage(constraint.getConstrainedElements().get(0), markup));\n }\n message.append(\" then it \").append(markup\n ? \"\"\n : \"\").append(\n markup\n ? \"\"\n : \"\").append(keyword).append(\n markup\n ? \" \"\n : \" \");\n message.append(computeConformanceMessage(constraint.getConstrainedElements().get(1), markup));\n message.append(markup\n ? \"\"\n : \"\");\n } else {\n if (markup) {\n message.append(\"
      \");\n }\n for (Element element : constraint.getConstrainedElements()) {\n message.append(LI[0]);\n message.append(computeConformanceMessage(element, markup));\n message.append(LI[1]);\n }\n if (markup) {\n message.append(\"
    \");\n }\n }\n appendConformanceRuleIds(constraint, message, markup);\n return message.toString();\n }\n private static boolean containsSeverityWord(String text) {\n return text.indexOf(\"SHALL\") >= 0 || text.indexOf(\"SHOULD\") >= 0 || text.indexOf(\"MAY\") >= 0;\n }\n private static String replaceSeverityWithBold(String input) {\n String output;\n output = input.replaceAll(\"SHALL\", \"SHALL\");\n output = output.replaceAll(\"SHOULD\", \"SHOULD\");\n output = output.replaceAll(\"MAY\", \"MAY\");\n output = output.replaceAll(\"\\\\SHALL\\\\ NOT\", \"SHALL NOT\");\n output = output.replaceAll(\"\\\\SHOULD\\\\ NOT\", \"SHOULD NOT\");\n return output;\n }\n /**\n * FindResourcesByNameVisitor searches the resource for resources of a particular name\n * You would think there was a method for this already but i could not find it\n *\n * @author seanmuir\n *\n */\n public static class FindResourcesByNameVisitor implements IResourceVisitor {\n private String resourceName;\n private ArrayList resources = new ArrayList();\n /**\n * @return the resources\n */\n public ArrayList getResources() {\n return resources;\n }\n /**\n * @param resourceName\n */\n public FindResourcesByNameVisitor(String resourceName) {\n super();\n this.resourceName = resourceName;\n }\n /*\n * (non-Javadoc)\n *\n * @see org.eclipse.core.resources.IResourceVisitor#visit(org.eclipse.core.resources.IResource)\n */\n public boolean visit(IResource arg0) throws CoreException {\n if (resourceName != null && resourceName.equals(arg0.getName())) {\n resources.add(arg0);\n }\n return true;\n }\n }\n public static IProject getElementModelProject(Element element) {\n try {\n Package elementPackage = UMLUtil.getTopPackage(element);\n if (elementPackage != null && elementPackage.eResource() != null) {\n FindResourcesByNameVisitor visitor = new FindResourcesByNameVisitor(\n elementPackage.eResource().getURI().lastSegment());\n IWorkspace iw = org.eclipse.core.resources.ResourcesPlugin.getWorkspace();\n iw.getRoot().accept(visitor);\n if (!visitor.getResources().isEmpty()) {\n return visitor.getResources().get(0).getProject();\n }\n }\n } catch (CoreException e) {\n // If there is an issue with the workspace - return null\n }\n return null;\n }\n public static IProject getModelDocProject(IProject modelProject) {\n if (modelProject != null && modelProject.exists()) {\n return org.eclipse.core.resources.ResourcesPlugin.getWorkspace().getRoot().getProject(\n modelProject.getName().replace(\".model\", \".doc\"));\n }\n return null;\n }\n /**\n * computeXref returns the XREF for DITA publication\n *\n * TODO Refactor and move out of model util\n *\n * @param source\n * @param target\n * @return\n */\n public static String computeXref(Element source, Classifier target) {\n if (target == null) {\n return null;\n }\n if (target instanceof Enumeration) {\n return computeTerminologyXref(source, (Enumeration) target);\n }\n if (UMLUtil.isSameProject(source, target)) {\n return \"../\" + normalizeCodeName(target.getName()) + \".dita\";\n }\n // If the model project is available (should be) and the dita content is part of the doc project\n if (!isCDAModel(target)) {\n IProject sourceProject = getElementModelProject(source);\n sourceProject = getModelDocProject(sourceProject);\n IProject targetProject = getElementModelProject(target);\n targetProject = getModelDocProject(targetProject);\n if (targetProject != null && sourceProject != null) {\n IPath projectPath = new Path(\"/dita/classes/\" + targetProject.getName());\n IFolder referenceDitaFolder = sourceProject.getFolder(projectPath);\n if (referenceDitaFolder.exists()) {\n return \"../\" + targetProject.getName() + \"/classes/\" + normalizeCodeName(target.getName()) +\n \".dita\";\n }\n }\n String pathFolder = \"classes\";\n String basePackage = \"\";\n String prefix = \"\";\n String packageName = target.getNearestPackage().getName();\n if (RIMModelUtil.RIM_PACKAGE_NAME.equals(packageName)) {\n basePackage = \"org.openhealthtools.mdht.uml.hl7.rim\";\n } else if (CDA_PACKAGE_NAME.equals(packageName)) {\n basePackage = \"org.openhealthtools.mdht.uml.cda\";\n } else {\n basePackage = getModelBasePackage(target);\n prefix = getModelNamespacePrefix(target);\n }\n if (basePackage == null || basePackage.trim().length() == 0) {\n basePackage = \"org.openhealthtools.mdht.uml.cda\";\n }\n if (prefix != null && prefix.trim().length() > 0) {\n prefix += \".\";\n }\n return INFOCENTER_URL + \"/topic/\" + basePackage + \".\" + prefix + \"doc/\" + pathFolder + \"/\" +\n normalizeCodeName(target.getName()) + \".html\";\n }\n return null;\n }\n protected static String computeTerminologyXref(Element source, Enumeration target) {\n String href = null;\n if (UMLUtil.isSameProject(source, target)) {\n href = \"../../terminology/\" + normalizeCodeName(target.getName()) + \".dita\";\n }\n return href;\n }\n public static Property getNavigableEnd(Association association) {\n Property navigableEnd = null;\n for (Property end : association.getMemberEnds()) {\n if (end.isNavigable()) {\n if (navigableEnd != null) {\n return null; // multiple navigable ends\n }\n navigableEnd = end;\n }\n }\n return navigableEnd;\n }\n /**\n * getExtensionNamespace returns the name space from a extension package in the CDA model\n *\n * @param type\n * @return\n */\n private static String getExtensionNamespace(Type type) {\n String nameSpace = null;\n if (type != null && type.getNearestPackage() != null &&\n !CDA_PACKAGE_NAME.equals(type.getNearestPackage().getName())) {\n Stereotype ecoreStereotype = type.getNearestPackage().getAppliedStereotype(EPACKAGE);\n if (ecoreStereotype != null) {\n Object object = type.getNearestPackage().getValue(ecoreStereotype, NSPREFIX);\n if (object instanceof String) {\n nameSpace = (String) object;\n }\n }\n }\n return nameSpace;\n }\n public static String getNameSpacePrefix(Class cdaSourceClass) {\n if (cdaSourceClass != null && cdaSourceClass.getPackage() != null &&\n !CDA_PACKAGE_NAME.equals(cdaSourceClass.getPackage().getName())) {\n Stereotype ecoreStereotype = cdaSourceClass.getPackage().getAppliedStereotype(EPACKAGE);\n if (ecoreStereotype != null) {\n Object object = cdaSourceClass.getPackage().getValue(ecoreStereotype, NSPREFIX);\n if (object instanceof String) {\n return (String) object;\n }\n }\n }\n return null;\n }\n /**\n * getCDAElementName - Returns the CDA Element name as a string\n *\n * @TODO Refactor to use org.openhealthtools.mdht.uml.transform.ecore.TransformAbstract.getInitialProperty(Property)\n *\n * Currently walk the redefines to see if we can match the CDA property using the name and type\n * If none found - for backwards compatibility we look for a property in the base class with a matching type which is potential error prone\n * If none still - leverage the getassociation\n *\n * @param property\n * @return\n */\n public static String getCDAElementName(Property property) {\n String elementName = null;\n if (property.getType() instanceof Class) {\n Class cdaSourceClass = getCDAClass(property.getClass_());\n if (cdaSourceClass != null) {\n // First check for definitions\n for (Property redefinedProperty : property.getRedefinedProperties()) {\n // This will never succeed for associations, does not include ActRelationship\n if (redefinedProperty.getType() != null) {\n Property cdaProperty = cdaSourceClass.getOwnedAttribute(\n redefinedProperty.getName(), getCDAClass((Classifier) redefinedProperty.getType()));\n if (cdaProperty != null && cdaProperty.getName() != null) {\n String modelPrefix = getExtensionNamespace(cdaProperty.getType());\n elementName = !StringUtils.isEmpty(modelPrefix)\n ? modelPrefix + \":\" + cdaProperty.getName()\n : cdaProperty.getName();\n break;\n }\n }\n }\n // Next check using property type and name\n if (elementName == null) {\n Property cdaProperty = cdaSourceClass.getOwnedAttribute(\n property.getName(), getCDAClass((Classifier) property.getType()));\n if (cdaProperty != null && cdaProperty.getName() != null) {\n String modelPrefix = getExtensionNamespace(cdaProperty.getType());\n elementName = !StringUtils.isEmpty(modelPrefix)\n ? modelPrefix + \":\" + cdaProperty.getName()\n : cdaProperty.getName();\n }\n }\n // Ultimately use original logic for backwards compatibility\n if (elementName == null) {\n Property cdaProperty = cdaSourceClass.getOwnedAttribute(\n null, getCDAClass((Classifier) property.getType()));\n if (cdaProperty != null && cdaProperty.getName() != null) {\n String modelPrefix = getExtensionNamespace(cdaProperty.getType());\n elementName = !StringUtils.isEmpty(modelPrefix)\n ? modelPrefix + \":\" + cdaProperty.getName()\n : cdaProperty.getName();\n }\n }\n }\n }\n // look for CDA association class element name, e.g. \"component\"\n if (elementName == null) {\n elementName = getCDAAssociationElementName(property);\n }\n if (elementName == null) {\n elementName = property.getName();\n }\n return elementName;\n }\n public static String getCDAAssociationElementName(Property property) {\n Class cdaSourceClass = getCDAClass(property.getClass_());\n Class endType = (property.getType() instanceof Class)\n ? (Class) property.getType()\n : null;\n Class cdaTargetClass = endType != null\n ? getCDAClass(endType)\n : null;\n // This is incomplete determination of XML element name, but same logic as used in model transform\n String elementName = null;\n if (cdaSourceClass == null) {\n elementName = property.getName();\n } else if (\"ClinicalDocument\".equals(cdaSourceClass.getName()) &&\n (CDAModelUtil.isSection(cdaTargetClass) || CDAModelUtil.isClinicalStatement(cdaTargetClass))) {\n elementName = \"component\";\n } else if (CDAModelUtil.isSection(cdaSourceClass) && (CDAModelUtil.isSection(cdaTargetClass))) {\n elementName = \"component\";\n } else if (CDAModelUtil.isSection(cdaSourceClass) &&\n (CDAModelUtil.isClinicalStatement(cdaTargetClass) || CDAModelUtil.isEntry(cdaTargetClass))) {\n elementName = \"entry\";\n } else if (CDAModelUtil.isOrganizer(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) {\n elementName = \"component\";\n } else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) &&\n CDAModelUtil.isClinicalStatement(cdaTargetClass)) {\n elementName = \"entryRelationship\";\n } else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && cdaTargetClass != null &&\n \"ParticipantRole\".equals(cdaTargetClass.getName())) {\n elementName = \"participant\";\n } else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && cdaTargetClass != null &&\n \"AssignedEntity\".equals(cdaTargetClass.getName())) {\n elementName = \"performer\";\n }\n return elementName;\n }\n private static String getMultiplicityRange(Property property) {\n StringBuffer message = new StringBuffer();\n String lower = Integer.toString(property.getLower());\n String upper = property.getUpper() == -1\n ? \"*\"\n : Integer.toString(property.getUpper());\n message.append(\" [\").append(lower).append(\"..\").append(upper).append(\"]\");\n return message.toString();\n }\n private static String getMultiplicityText(Property property) {\n StringBuffer message = new StringBuffer();\n if (property.getLower() == property.getUpper()) {\n // Upper and lower equal and not zero\n if (property.getLower() != 0) {\n message.append(\"exactly \").append(convertNumberToWords(property.getUpper()));\n }\n } else if (property.getLower() == 0) {\n // Lower is zero\n if (property.getUpper() == 0) {\n } else if (property.getUpper() == 1) {\n message.append(\"zero or one\");\n } else if (property.getUpper() == -1) {\n message.append(\"zero or more\");\n } else {\n message.append(\"not more than \" + convertNumberToWords(property.getUpper()));\n }\n } else if (property.getLower() == 1) {\n // Lower is one\n if (property.getUpper() == -1) {\n message.append(\"at least one\");\n } else {\n message.append(\n \"at least \" + convertNumberToWords(property.getLower()) + \" and not more than \" +\n convertNumberToWords(property.getUpper()));\n }\n } else {\n // Lower is greater then 1\n message.append(\"at least \" + convertNumberToWords(property.getLower()));\n if (property.getUpper() != -1) {\n message.append(\" and not more than \" + convertNumberToWords(property.getUpper()));\n }\n }\n return message.toString();\n }\n // This snippet may be used freely, as long as the authorship note remains in the source code.\n private static final String[] lowNames = {\n \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\",\n \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n private static final String[] tensNames = {\n \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n private static final String[] bigNames = { \"thousand\", \"million\", \"billion\" };\n private static String convertNumberToWords(int n) {\n if (n < 0) {\n return \"minus \" + convertNumberToWords(-n);\n }\n if (n <= 999) {\n return convert999(n);\n }\n String s = null;\n int t = 0;\n while (n > 0) {\n if (n % 1000 != 0) {\n String s2 = convert999(n % 1000);\n if (t > 0) {\n s2 = s2 + \" \" + bigNames[t - 1];\n }\n if (s == null) {\n s = s2;\n } else {\n s = s2 + \", \" + s;\n }\n }\n n /= 1000;\n t++;\n }\n return s;\n }\n // Range 0 to 999.\n private static String convert999(int n) {\n String s1 = lowNames[n / 100] + \" hundred\";\n String s2 = convert99(n % 100);\n if (n <= 99) {\n return s2;\n } else if (n % 100 == 0) {\n return s1;\n } else {\n return s1 + \" \" + s2;\n }\n }\n // Range 0 to 99.\n private static String convert99(int n) {\n if (n < 20) {\n return lowNames[n];\n }\n String s = tensNames[n / 10 - 2];\n if (n % 10 == 0) {\n return s;\n }\n return s + \"-\" + lowNames[n % 10];\n }\n public static boolean isXMLAttribute(Property property) {\n Property cdaProperty = getCDAProperty(property);\n if (cdaProperty != null) {\n Stereotype eAttribute = cdaProperty.getAppliedStereotype(\"Ecore::EAttribute\");\n if (eAttribute != null) {\n return true;\n }\n }\n return false;\n }\n private static String getMultiplicityRange(Class template) {\n String templateId = null;\n Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);\n if (hl7Template != null && template.hasValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_MULTIPLICITY)) {\n templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_MULTIPLICITY);\n } else {\n for (Classifier parent : template.getGenerals()) {\n templateId = getMultiplicityRange((Class) parent);\n if (templateId != null) {\n break;\n }\n }\n }\n return templateId;\n }\n public static String getTemplateId(Class template) {\n String templateId = null;\n Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);\n if (hl7Template != null) {\n templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_TEMPLATE_ID);\n } else {\n for (Classifier parent : template.getGenerals()) {\n templateId = getTemplateId((Class) parent);\n if (templateId != null) {\n break;\n }\n }\n }\n return templateId;\n }\n public static String getTemplateVersion(Class template) {\n String templateVersion = null;\n Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);\n if (hl7Template != null) {\n templateVersion = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_VERSION);\n } else {\n for (Classifier parent : template.getGenerals()) {\n templateVersion = getTemplateId((Class) parent);\n if (templateVersion != null) {\n break;\n }\n }\n }\n return templateVersion;\n }\n public static String getModelPrefix(Element element) {\n String prefix = null;\n Package thePackage = UMLUtil.getTopPackage(element);\n if (thePackage != null) {\n Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(\n thePackage, ICDAProfileConstants.CODEGEN_SUPPORT);\n if (codegenSupport != null) {\n prefix = (String) thePackage.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_PREFIX);\n } else if (CDA_PACKAGE_NAME.equals(thePackage.getName())) {\n prefix = \"CDA\";\n } else if (RIMModelUtil.RIM_PACKAGE_NAME.equals(thePackage.getName())) {\n prefix = \"RIM\";\n }\n }\n return prefix != null\n ? prefix\n : \"\";\n }\n public static String getModelNamespacePrefix(Element element) {\n String prefix = null;\n Package model = UMLUtil.getTopPackage(element);\n Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);\n if (codegenSupport != null) {\n prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_PREFIX);\n }\n return prefix;\n }\n public static String getModelBasePackage(Element element) {\n String basePackage = null;\n Package model = UMLUtil.getTopPackage(element);\n Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);\n if (codegenSupport != null) {\n basePackage = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_BASE_PACKAGE);\n }\n return basePackage;\n }\n public static String getEcorePackageURI(Element element) {\n String nsURI = null;\n Package model = UMLUtil.getTopPackage(element);\n Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);\n if (codegenSupport != null) {\n nsURI = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_URI);\n }\n if (nsURI == null) {\n // for base models without codegenSupport\n if (model.getName().equals(\"cda\")) {\n nsURI = \"urn:hl7-org:v3\";\n } else if (model.getName().equals(\"datatypes\")) {\n nsURI = \"http:\n } else if (model.getName().equals(\"vocab\")) {\n nsURI = \"http:\n }\n }\n return nsURI;\n }\n public static String getPrefixedSplitName(NamedElement element) {\n StringBuffer buffer = new StringBuffer();\n String modelPrefix = getModelPrefix(element);\n if (modelPrefix != null && modelPrefix.length() > 0) {\n buffer.append(modelPrefix).append(\" \");\n }\n buffer.append(UMLUtil.splitName(element));\n return buffer.toString();\n }\n /**\n * Returns a list conformance rule IDs.\n */\n public static List getConformanceRuleIdList(Element element) {\n List ruleIds = new ArrayList();\n Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);\n if (validationSupport != null) {\n Validation validation = (Validation) element.getStereotypeApplication(validationSupport);\n for (String ruleId : validation.getRuleId()) {\n ruleIds.add(ruleId);\n }\n }\n return ruleIds;\n }\n protected static void appendTerminologyConformanceRuleIds(Property property, StringBuffer message, boolean markup) {\n String ruleIds = getTerminologyConformanceRuleIds(property);\n if (ruleIds.length() > 0) {\n message.append(\" (\");\n message.append(ruleIds);\n message.append(\")\");\n }\n }\n protected static void appendConformanceRuleIds(Property property, StringBuffer message, boolean markup) {\n String ruleIds = getConformanceRuleIds(property);\n if (ruleIds.length() > 0) {\n message.append(\" (\");\n message.append(ruleIds);\n message.append(\")\");\n }\n }\n protected static void appendConformanceRuleIds(Association association, StringBuffer message, boolean markup) {\n String ruleIds = getConformanceRuleIds(association);\n if (ruleIds.length() > 0) {\n message.append(\" (\");\n message.append(ruleIds);\n message.append(\")\");\n }\n }\n protected static void appendConformanceRuleIds(Element element, StringBuffer message, boolean markup) {\n String ruleIds = getConformanceRuleIds(element);\n if (ruleIds.length() > 0) {\n message.append(\" (\");\n message.append(ruleIds);\n message.append(\")\");\n }\n }\n protected static void appendConformanceRuleIds(Element element, Stereotype stereotype, StringBuffer message,\n boolean markup) {\n String ruleIds = getConformanceRuleIds(element, stereotype);\n if (ruleIds.length() > 0) {\n message.append(\" (\");\n message.append(ruleIds);\n message.append(\")\");\n }\n }\n /**\n * Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.\n */\n public static String getConformanceRuleIds(Property property) {\n Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(\n property, ICDAProfileConstants.PROPERTY_VALIDATION);\n return getConformanceRuleIds(property, validationSupport);\n }\n /**\n * Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.\n */\n public static String getTerminologyConformanceRuleIds(Property property) {\n Stereotype terminologyConstraint = getTerminologyConstraint(property);\n return getConformanceRuleIds(property, terminologyConstraint);\n }\n /**\n * Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.\n */\n public static String getConformanceRuleIds(Association association) {\n Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(\n association, ICDAProfileConstants.ASSOCIATION_VALIDATION);\n return getConformanceRuleIds(association, validationSupport);\n }\n /**\n * Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.\n */\n public static String getConformanceRuleIds(Element element) {\n Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);\n return getConformanceRuleIds(element, validationSupport);\n }\n public static String getConformanceRuleIds(Element element, Stereotype validationSupport) {\n StringBuffer ruleIdDisplay = new StringBuffer();\n if (validationSupport != null) {\n Validation validation = (Validation) element.getStereotypeApplication(validationSupport);\n for (String ruleId : validation.getRuleId()) {\n if (ruleIdDisplay.length() > 0) {\n ruleIdDisplay.append(\", \");\n }\n ruleIdDisplay.append(ruleId);\n }\n }\n return ruleIdDisplay.toString();\n }\n public static Stereotype getTerminologyConstraint(Element element) {\n Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(\n element, ITermProfileConstants.CONCEPT_DOMAIN_CONSTRAINT);\n if (stereotype == null) {\n stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);\n }\n if (stereotype == null) {\n stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ITermProfileConstants.VALUE_SET_CONSTRAINT);\n }\n return stereotype;\n }\n public static boolean hasValidationSupport(Element element) {\n Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);\n return validationSupport != null;\n }\n /**\n * @deprecated Use {@link #getValidationSeverity(Property, String)} to get the severity for a specific validation stereotype.\n * If necessary, this can be the abstract {@link ICDAProfileConstants#VALIDATION Validation} stereotype to get any available\n * validation severity.\n */\n @Deprecated\n public static String getValidationSeverity(Property property) {\n return getValidationSeverity(property, ICDAProfileConstants.PROPERTY_VALIDATION);\n }\n public static String getValidationSeverity(Property property, String validationStereotypeName) {\n Stereotype validationStereotype = CDAProfileUtil.getAppliedCDAStereotype(property, validationStereotypeName);\n return getValidationSeverity(property, validationStereotype);\n }\n public static String getValidationSeverity(Element element) {\n // use first available validation stereotype\n return getValidationSeverity(element, ICDAProfileConstants.VALIDATION);\n }\n public static String getValidationSeverity(Element element, String validationStereotypeName) {\n Stereotype validationStereotype = CDAProfileUtil.getAppliedCDAStereotype(element, validationStereotypeName);\n return getValidationSeverity(element, validationStereotype);\n }\n public static String getValidationSeverity(Element element, Stereotype validationStereotype) {\n String severity = null;\n if ((validationStereotype != null) && CDAProfileUtil.isValidationStereotype(validationStereotype)) {\n Object value = element.getValue(validationStereotype, ICDAProfileConstants.VALIDATION_SEVERITY);\n if (value instanceof EnumerationLiteral) {\n severity = ((EnumerationLiteral) value).getName();\n } else if (value instanceof Enumerator) {\n severity = ((Enumerator) value).getName();\n }\n }\n return severity;\n }\n public static String getValidationKeywordWithPropertyRange(Property property) {\n String keyword = getValidationKeyword(property);\n return addShallNot(keyword, property);\n }\n public static String getValidationKeyword(Property property) {\n String severity = getValidationSeverity(property, ICDAProfileConstants.PROPERTY_VALIDATION);\n if (severity == null) {\n // get other validation stereotype, usually for terminology\n severity = getValidationSeverity((Element) property);\n }\n return getValidationKeyword(severity);\n }\n public static String getValidationKeywordWithPropertyRange(Element element, Property property) {\n // use first available validation stereotype\n String keyword = getValidationKeyword(element);\n return addShallNot(keyword, property);\n }\n private static String addShallNot(String keyword, Property property) {\n if (property.getLower() == 0 && property.getUpper() == 0 &&\n (\"SHALL\".equals(keyword) || \"SHOULD\".equals(keyword))) {\n keyword += \" NOT\";\n }\n return keyword;\n }\n public static String getValidationKeyword(Element element) {\n // use first available validation stereotype\n String severity = getValidationSeverity(element);\n return getValidationKeyword(severity);\n }\n public static String getValidationKeyword(Element element, Stereotype validationStereotype) {\n String severity = getValidationSeverity(element, validationStereotype);\n return getValidationKeyword(severity);\n }\n private static String getValidationKeyword(String severity) {\n String keyword = null;\n if (SEVERITY_INFO.equals(severity)) {\n keyword = \"MAY\";\n } else if (SEVERITY_WARNING.equals(severity)) {\n keyword = \"SHOULD\";\n } else if (SEVERITY_ERROR.equals(severity)) {\n keyword = \"SHALL\";\n }\n return keyword;\n }\n public static void setValidationMessage(Element constrainedElement, String message) {\n Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(\n constrainedElement, ICDAProfileConstants.VALIDATION);\n if (validationSupport != null) {\n constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE, message);\n }\n }\n protected static String getLiteralValue(Element element, Stereotype stereotype, String propertyName) {\n Object value = element.getValue(stereotype, propertyName);\n String name = null;\n if (value instanceof EnumerationLiteral) {\n name = ((EnumerationLiteral) value).getName();\n } else if (value instanceof Enumerator) {\n name = ((Enumerator) value).getName();\n }\n return name;\n }\n protected static String getLiteralValueLabel(Element element, Stereotype stereotype, String propertyName,\n Enumeration umlEnumeration) {\n Object value = element.getValue(stereotype, propertyName);\n String name = null;\n if (value instanceof EnumerationLiteral) {\n name = ((EnumerationLiteral) value).getLabel();\n } else if (value instanceof Enumerator) {\n name = ((Enumerator) value).getName();\n if (umlEnumeration != null) {\n name = umlEnumeration.getOwnedLiteral(name).getLabel();\n }\n }\n return name;\n }\n public static String fixNonXMLCharacters(String text) {\n if (text == null) {\n return null;\n }\n StringBuffer newText = new StringBuffer();\n for (int i = 0; i < text.length(); i++) {\n // test for unicode characters from copy/paste of MS Word text\n if (text.charAt(i) == '\\u201D') {\n newText.append(\"\\\"\");\n } else if (text.charAt(i) == '\\u201C') {\n newText.append(\"\\\"\");\n } else if (text.charAt(i) == '\\u2019') {\n newText.append(\"'\");\n } else if (text.charAt(i) == '\\u2018') {\n newText.append(\"'\");\n } else {\n newText.append(text.charAt(i));\n }\n }\n return newText.toString();\n }\n public static String escapeMarkupCharacters(String text) {\n if (text == null) {\n return null;\n }\n text = fixNonXMLCharacters(text);\n StringBuffer newText = new StringBuffer();\n for (int i = 0; i < text.length(); i++) {\n if (text.charAt(i) == '<') {\n newText.append(\"&lt;\");\n } else if (text.charAt(i) == '>') {\n newText.append(\"&gt;\");\n } else {\n newText.append(text.charAt(i));\n }\n }\n return newText.toString();\n }\n public static String normalizeCodeName(String name) {\n String result = \"\";\n String[] parts = name.split(\" \");\n for (String part : parts) {\n result += part.substring(0, 1).toUpperCase() + part.substring(1);\n }\n result = UML2Util.getValidJavaIdentifier(result);\n return result;\n }\n private static String mandatoryOrNotMessage(Property curProperty) {\n // capture if allows nullFlavor or not\n boolean mandatory = CDAProfileUtil.isMandatory(curProperty);\n // mandatory implies nullFlavor is NOT allowed \", where the @code \"\n // non-mandatory implies nullFlavor is allowed \", which \"\n // return the proper message based on mandatory or not\n return mandatory\n ? \", where the @code \"\n : \", which \";\n }\n public static boolean isInlineClass(Class _class) {\n Inline inline = CDAProfileUtil.getInline(_class);\n if (inline != null) {\n return true;\n }\n if (_class.getOwner() instanceof Class) {\n return true;\n }\n for (Comment comment : _class.getOwnedComments()) {\n if (comment.getBody().startsWith(\"INLINE\")) {\n return true;\n }\n }\n return false;\n }\n public static String getInlineFilter(Class inlineClass) {\n Inline inline = CDAProfileUtil.getInline(inlineClass);\n if (inline != null) {\n return inline.getFilter() != null\n ? inline.getFilter()\n : \"\";\n }\n String filter = \"\";\n for (Comment comment : inlineClass.getOwnedComments()) {\n if (comment.getBody().startsWith(\"INLINE&\")) {\n String[] temp = comment.getBody().split(\"&\");\n if (temp.length == 2) {\n filter = String.format(\"->select(%s)\", temp[1]);\n }\n break;\n }\n }\n if (\"\".equals(filter)) {\n // search hierarchy\n for (Classifier next : inlineClass.getGenerals()) {\n if (next instanceof Class) {\n filter = getInlineFilter((Class) next);\n if (!\"\".equals(filter)) {\n break;\n }\n }\n }\n }\n return filter;\n }\n public static boolean isPublishSeperately(Class _class) {\n boolean publish = false;\n Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(_class, ICDAProfileConstants.INLINE);\n if (stereotype != null) {\n Boolean result = (Boolean) _class.getValue(stereotype, \"publishSeperately\");\n publish = result.booleanValue();\n }\n return publish;\n }\n}"}}},{"rowIdx":1261,"cells":{"answer":{"kind":"string","value":"package com.raoulvdberge.refinedstorage.apiimpl.network.node;\nimport com.raoulvdberge.refinedstorage.RS;\nimport com.raoulvdberge.refinedstorage.RSBlocks;\nimport com.raoulvdberge.refinedstorage.RSItems;\nimport com.raoulvdberge.refinedstorage.api.network.INetwork;\nimport com.raoulvdberge.refinedstorage.api.network.grid.GridType;\nimport com.raoulvdberge.refinedstorage.api.network.grid.IGrid;\nimport com.raoulvdberge.refinedstorage.api.network.grid.IGridNetworkAware;\nimport com.raoulvdberge.refinedstorage.api.network.grid.IGridTab;\nimport com.raoulvdberge.refinedstorage.api.network.grid.handler.IFluidGridHandler;\nimport com.raoulvdberge.refinedstorage.api.network.grid.handler.IItemGridHandler;\nimport com.raoulvdberge.refinedstorage.api.network.item.INetworkItem;\nimport com.raoulvdberge.refinedstorage.api.network.item.NetworkItemAction;\nimport com.raoulvdberge.refinedstorage.api.network.security.Permission;\nimport com.raoulvdberge.refinedstorage.api.storage.IStorageCache;\nimport com.raoulvdberge.refinedstorage.api.storage.IStorageCacheListener;\nimport com.raoulvdberge.refinedstorage.api.util.IComparer;\nimport com.raoulvdberge.refinedstorage.api.util.IFilter;\nimport com.raoulvdberge.refinedstorage.apiimpl.API;\nimport com.raoulvdberge.refinedstorage.apiimpl.storage.StorageCacheListenerGridFluid;\nimport com.raoulvdberge.refinedstorage.apiimpl.storage.StorageCacheListenerGridItem;\nimport com.raoulvdberge.refinedstorage.block.BlockGrid;\nimport com.raoulvdberge.refinedstorage.inventory.ItemHandlerBase;\nimport com.raoulvdberge.refinedstorage.inventory.ItemHandlerFilter;\nimport com.raoulvdberge.refinedstorage.inventory.ItemHandlerListenerNetworkNode;\nimport com.raoulvdberge.refinedstorage.inventory.ItemValidatorBasic;\nimport com.raoulvdberge.refinedstorage.item.ItemPattern;\nimport com.raoulvdberge.refinedstorage.tile.data.TileDataManager;\nimport com.raoulvdberge.refinedstorage.tile.grid.TileGrid;\nimport com.raoulvdberge.refinedstorage.util.StackUtils;\nimport net.minecraft.entity.player.EntityPlayer;\nimport net.minecraft.entity.player.EntityPlayerMP;\nimport net.minecraft.inventory.*;\nimport net.minecraft.item.ItemStack;\nimport net.minecraft.item.crafting.CraftingManager;\nimport net.minecraft.item.crafting.IRecipe;\nimport net.minecraft.nbt.NBTTagCompound;\nimport net.minecraft.util.NonNullList;\nimport net.minecraft.util.math.BlockPos;\nimport net.minecraft.world.World;\nimport net.minecraftforge.fml.common.FMLCommonHandler;\nimport net.minecraftforge.items.IItemHandler;\nimport net.minecraftforge.items.IItemHandlerModifiable;\nimport net.minecraftforge.items.ItemHandlerHelper;\nimport net.minecraftforge.items.wrapper.CombinedInvWrapper;\nimport net.minecraftforge.items.wrapper.InvWrapper;\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class NetworkNodeGrid extends NetworkNode implements IGridNetworkAware {\n public static final String ID = \"grid\";\n public static final String NBT_VIEW_TYPE = \"ViewType\";\n public static final String NBT_SORTING_DIRECTION = \"SortingDirection\";\n public static final String NBT_SORTING_TYPE = \"SortingType\";\n public static final String NBT_SEARCH_BOX_MODE = \"SearchBoxMode\";\n public static final String NBT_OREDICT_PATTERN = \"OredictPattern\";\n public static final String NBT_TAB_SELECTED = \"TabSelected\";\n public static final String NBT_TAB_PAGE = \"TabPage\";\n public static final String NBT_SIZE = \"Size\";\n public static final String NBT_PROCESSING_PATTERN = \"ProcessingPattern\";\n private Container craftingContainer = new Container() {\n @Override\n public boolean canInteractWith(EntityPlayer player) {\n return false;\n }\n @Override\n public void onCraftMatrixChanged(IInventory inventory) {\n onCraftingMatrixChanged();\n }\n };\n private IRecipe currentRecipe;\n private InventoryCrafting matrix = new InventoryCrafting(craftingContainer, 3, 3);\n private InventoryCraftResult result = new InventoryCraftResult();\n private ItemHandlerBase matrixProcessing = new ItemHandlerBase(9 * 2, new ItemHandlerListenerNetworkNode(this));\n private ItemHandlerBase patterns = new ItemHandlerBase(2, new ItemHandlerListenerNetworkNode(this), new ItemValidatorBasic(RSItems.PATTERN)) {\n @Override\n protected void onContentsChanged(int slot) {\n super.onContentsChanged(slot);\n ItemStack pattern = getStackInSlot(slot);\n if (slot == 1 && !pattern.isEmpty()) {\n boolean isPatternProcessing = ItemPattern.isProcessing(pattern);\n if (isPatternProcessing && isProcessingPattern()) {\n for (int i = 0; i < 9; ++i) {\n matrixProcessing.setStackInSlot(i, StackUtils.nullToEmpty(ItemPattern.getInputSlot(pattern, i)));\n }\n for (int i = 0; i < 9; ++i) {\n matrixProcessing.setStackInSlot(9 + i, StackUtils.nullToEmpty(ItemPattern.getOutputSlot(pattern, i)));\n }\n } else if (!isPatternProcessing && !isProcessingPattern()) {\n for (int i = 0; i < 9; ++i) {\n matrix.setInventorySlotContents(i, StackUtils.nullToEmpty(ItemPattern.getInputSlot(pattern, i)));\n }\n }\n }\n }\n @Override\n public int getSlotLimit(int slot) {\n return slot == 1 ? 1 : super.getSlotLimit(slot);\n }\n @Nonnull\n @Override\n public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) {\n // Allow in slot 0\n // Disallow in slot 1\n // Only allow in slot 1 when it isn't a blank pattern\n // This makes it so that written patterns can be re-inserted in slot 1 to be overwritten again\n // This makes it so that blank patterns can't be inserted in slot 1 through hoppers.\n if (slot == 0 || stack.getTagCompound() != null) {\n return super.insertItem(slot, stack, simulate);\n }\n return stack;\n }\n };\n private List filters = new ArrayList<>();\n private List tabs = new ArrayList<>();\n private ItemHandlerFilter filter = new ItemHandlerFilter(filters, tabs, new ItemHandlerListenerNetworkNode(this));\n private GridType type;\n private int viewType = VIEW_TYPE_NORMAL;\n private int sortingDirection = SORTING_DIRECTION_DESCENDING;\n private int sortingType = SORTING_TYPE_QUANTITY;\n private int searchBoxMode = SEARCH_BOX_MODE_NORMAL;\n private int size = SIZE_STRETCH;\n private int tabSelected = -1;\n private int tabPage = 0;\n private boolean oredictPattern = false;\n private boolean processingPattern = false;\n public NetworkNodeGrid(World world, BlockPos pos) {\n super(world, pos);\n }\n @Override\n public int getEnergyUsage() {\n switch (getType()) {\n case NORMAL:\n return RS.INSTANCE.config.gridUsage;\n case CRAFTING:\n return RS.INSTANCE.config.craftingGridUsage;\n case PATTERN:\n return RS.INSTANCE.config.patternGridUsage;\n case FLUID:\n return RS.INSTANCE.config.fluidGridUsage;\n default:\n return 0;\n }\n }\n public void setViewType(int viewType) {\n this.viewType = viewType;\n }\n public void setSortingDirection(int sortingDirection) {\n this.sortingDirection = sortingDirection;\n }\n public void setSortingType(int sortingType) {\n this.sortingType = sortingType;\n }\n public void setSearchBoxMode(int searchBoxMode) {\n this.searchBoxMode = searchBoxMode;\n }\n public void setTabSelected(int tabSelected) {\n this.tabSelected = tabSelected;\n }\n public void setTabPage(int page) {\n this.tabPage = page;\n }\n public void setSize(int size) {\n this.size = size;\n }\n public boolean isOredictPattern() {\n return oredictPattern;\n }\n public void setOredictPattern(boolean oredictPattern) {\n this.oredictPattern = oredictPattern;\n }\n public boolean isProcessingPattern() {\n return world.isRemote ? TileGrid.PROCESSING_PATTERN.getValue() : processingPattern;\n }\n public void setProcessingPattern(boolean processingPattern) {\n this.processingPattern = processingPattern;\n }\n public GridType getType() {\n if (type == null && world.getBlockState(pos).getBlock() == RSBlocks.GRID) {\n type = (GridType) world.getBlockState(pos).getValue(BlockGrid.TYPE);\n }\n return type == null ? GridType.NORMAL : type;\n }\n @Override\n public IStorageCacheListener createListener(EntityPlayerMP player) {\n return getType() == GridType.FLUID ? new StorageCacheListenerGridFluid(player, network) : new StorageCacheListenerGridItem(player, network);\n }\n @Nullable\n @Override\n public IStorageCache getStorageCache() {\n return network != null ? (getType() == GridType.FLUID ? network.getFluidStorageCache() : network.getItemStorageCache()) : null;\n }\n @Nullable\n @Override\n public IItemGridHandler getItemHandler() {\n return network != null ? network.getItemGridHandler() : null;\n }\n @Nullable\n @Override\n public IFluidGridHandler getFluidHandler() {\n return network != null ? network.getFluidGridHandler() : null;\n }\n @Override\n public String getGuiTitle() {\n GridType type = getType();\n switch (type) {\n case CRAFTING:\n return \"gui.refinedstorage:crafting_grid\";\n case PATTERN:\n return \"gui.refinedstorage:pattern_grid\";\n case FLUID:\n return \"gui.refinedstorage:fluid_grid\";\n default:\n return \"gui.refinedstorage:grid\";\n }\n }\n public IItemHandler getPatterns() {\n return patterns;\n }\n @Override\n public IItemHandlerModifiable getFilter() {\n return filter;\n }\n @Override\n public List getFilters() {\n return filters;\n }\n @Override\n public List getTabs() {\n return tabs;\n }\n @Override\n public InventoryCrafting getCraftingMatrix() {\n return matrix;\n }\n @Override\n public InventoryCraftResult getCraftingResult() {\n return result;\n }\n public ItemHandlerBase getProcessingMatrix() {\n return matrixProcessing;\n }\n @Override\n public void onCraftingMatrixChanged() {\n if (currentRecipe == null || !currentRecipe.matches(matrix, world)) {\n currentRecipe = CraftingManager.findMatchingRecipe(matrix, world);\n }\n if (currentRecipe == null) {\n result.setInventorySlotContents(0, ItemStack.EMPTY);\n } else {\n result.setInventorySlotContents(0, currentRecipe.getCraftingResult(matrix));\n }\n markDirty();\n }\n @Override\n public void onRecipeTransfer(EntityPlayer player, ItemStack[][] recipe) {\n onRecipeTransfer(this, player, recipe);\n }\n public static void onRecipeTransfer(IGridNetworkAware grid, EntityPlayer player, ItemStack[][] recipe) {\n INetwork network = grid.getNetwork();\n if (network != null && grid.getType() == GridType.CRAFTING && !network.getSecurityManager().hasPermission(Permission.EXTRACT, player)) {\n return;\n }\n // First try to empty the crafting matrix\n for (int i = 0; i < grid.getCraftingMatrix().getSizeInventory(); ++i) {\n ItemStack slot = grid.getCraftingMatrix().getStackInSlot(i);\n if (!slot.isEmpty()) {\n // Only if we are a crafting grid. Pattern grids can just be emptied.\n if (grid.getType() == GridType.CRAFTING) {\n // If we are connected, try to insert into network. If it fails, stop.\n if (network != null) {\n if (network.insertItem(slot, slot.getCount(), true) != null) {\n return;\n } else {\n network.insertItem(slot, slot.getCount(), false);\n }\n } else {\n // If we aren't connected, try to insert into player inventory. If it fails, stop.\n if (!player.inventory.addItemStackToInventory(slot.copy())) {\n return;\n }\n }\n }\n grid.getCraftingMatrix().setInventorySlotContents(i, ItemStack.EMPTY);\n }\n }\n // Now let's fill the matrix\n for (int i = 0; i < grid.getCraftingMatrix().getSizeInventory(); ++i) {\n if (recipe[i] != null) {\n ItemStack[] possibilities = recipe[i];\n // If we are a crafting grid\n if (grid.getType() == GridType.CRAFTING) {\n boolean found = false;\n // If we are connected, first try to get the possibilities from the network\n if (network != null) {\n for (ItemStack possibility : possibilities) {\n ItemStack took = network.extractItem(possibility, 1, IComparer.COMPARE_NBT | (possibility.getItem().isDamageable() ? 0 : IComparer.COMPARE_DAMAGE), false);\n if (took != null) {\n grid.getCraftingMatrix().setInventorySlotContents(i, StackUtils.nullToEmpty(took));\n found = true;\n break;\n }\n }\n }\n // If we haven't found anything in the network (or we are disconnected), go look in the player inventory\n if (!found) {\n for (ItemStack possibility : possibilities) {\n for (int j = 0; j < player.inventory.getSizeInventory(); ++j) {\n if (API.instance().getComparer().isEqual(possibility, player.inventory.getStackInSlot(j), IComparer.COMPARE_NBT | (possibility.getItem().isDamageable() ? 0 : IComparer.COMPARE_DAMAGE))) {\n grid.getCraftingMatrix().setInventorySlotContents(i, ItemHandlerHelper.copyStackWithSize(player.inventory.getStackInSlot(j), 1));\n player.inventory.decrStackSize(j, 1);\n found = true;\n break;\n }\n }\n if (found) {\n break;\n }\n }\n }\n } else if (grid.getType() == GridType.PATTERN) {\n // If we are a pattern grid we can just set the slot\n grid.getCraftingMatrix().setInventorySlotContents(i, possibilities.length == 0 ? ItemStack.EMPTY : possibilities[0]);\n }\n }\n }\n }\n public void clearMatrix() {\n for (int i = 0; i < matrixProcessing.getSlots(); ++i) {\n matrixProcessing.setStackInSlot(i, ItemStack.EMPTY);\n }\n for (int i = 0; i < matrix.getSizeInventory(); ++i) {\n matrix.setInventorySlotContents(i, ItemStack.EMPTY);\n }\n }\n @Override\n public void onClosed(EntityPlayer player) {\n // NO OP\n }\n @Override\n public void onCrafted(EntityPlayer player) {\n onCrafted(this, world, player);\n }\n public static void onCrafted(IGridNetworkAware grid, World world, EntityPlayer player) {\n NonNullList remainder = CraftingManager.getRemainingItems(grid.getCraftingMatrix(), world);\n INetwork network = grid.getNetwork();\n InventoryCrafting matrix = grid.getCraftingMatrix();\n for (int i = 0; i < grid.getCraftingMatrix().getSizeInventory(); ++i) {\n ItemStack slot = matrix.getStackInSlot(i);\n if (i < remainder.size() && !remainder.get(i).isEmpty()) {\n // If there is no space for the remainder, dump it in the player inventory\n if (!slot.isEmpty() && slot.getCount() > 1) {\n if (!player.inventory.addItemStackToInventory(remainder.get(i).copy())) {\n ItemStack remainderStack = network == null ? remainder.get(i).copy() : network.insertItem(remainder.get(i).copy(), remainder.get(i).getCount(), false);\n if (remainderStack != null) {\n InventoryHelper.spawnItemStack(player.getEntityWorld(), player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ(), remainderStack);\n }\n }\n matrix.decrStackSize(i, 1);\n } else {\n matrix.setInventorySlotContents(i, remainder.get(i).copy());\n }\n } else if (!slot.isEmpty()) {\n if (slot.getCount() == 1 && network != null) {\n matrix.setInventorySlotContents(i, StackUtils.nullToEmpty(network.extractItem(slot, 1, false)));\n } else {\n matrix.decrStackSize(i, 1);\n }\n }\n }\n grid.onCraftingMatrixChanged();\n if (network != null) {\n INetworkItem networkItem = network.getNetworkItemHandler().getItem(player);\n if (networkItem != null) {\n networkItem.onAction(NetworkItemAction.ITEM_CRAFTED);\n }\n }\n }\n @Override\n public void onCraftedShift(EntityPlayer player) {\n onCraftedShift(this, player);\n }\n public static void onCraftedShift(IGridNetworkAware grid, EntityPlayer player) {\n List craftedItemsList = new ArrayList<>();\n int craftedItems = 0;\n ItemStack crafted = grid.getCraftingResult().getStackInSlot(0);\n while (true) {\n grid.onCrafted(player);\n craftedItemsList.add(crafted.copy());\n craftedItems += crafted.getCount();\n if (!API.instance().getComparer().isEqual(crafted, grid.getCraftingResult().getStackInSlot(0)) || craftedItems + crafted.getCount() > crafted.getMaxStackSize()) {\n break;\n }\n }\n INetwork network = grid.getNetwork();\n for (ItemStack craftedItem : craftedItemsList) {\n if (!player.inventory.addItemStackToInventory(craftedItem.copy())) {\n ItemStack remainder = network == null ? craftedItem : network.insertItem(craftedItem, craftedItem.getCount(), false);\n if (remainder != null) {\n InventoryHelper.spawnItemStack(player.getEntityWorld(), player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ(), remainder);\n }\n }\n }\n FMLCommonHandler.instance().firePlayerCraftingEvent(player, ItemHandlerHelper.copyStackWithSize(crafted, craftedItems), grid.getCraftingMatrix());\n }\n public void onCreatePattern() {\n if (canCreatePattern()) {\n if (patterns.getStackInSlot(1).isEmpty()) {\n patterns.extractItem(0, 1, false);\n }\n ItemStack pattern = new ItemStack(RSItems.PATTERN);\n ItemPattern.setOredict(pattern, oredictPattern);\n ItemPattern.setProcessing(pattern, processingPattern);\n if (processingPattern) {\n for (int i = 0; i < 18; ++i) {\n if (!matrixProcessing.getStackInSlot(i).isEmpty()) {\n if (i >= 9) {\n ItemPattern.setOutputSlot(pattern, i - 9, matrixProcessing.getStackInSlot(i));\n } else {\n ItemPattern.setInputSlot(pattern, i, matrixProcessing.getStackInSlot(i));\n }\n }\n }\n } else {\n for (int i = 0; i < 9; ++i) {\n ItemStack ingredient = matrix.getStackInSlot(i);\n if (!ingredient.isEmpty()) {\n ItemPattern.setInputSlot(pattern, i, ingredient);\n }\n }\n }\n patterns.setStackInSlot(1, pattern);\n }\n }\n private boolean isPatternAvailable() {\n return !(patterns.getStackInSlot(0).isEmpty() && patterns.getStackInSlot(1).isEmpty());\n }\n public boolean canCreatePattern() {\n if (!isPatternAvailable()) {\n return false;\n }\n if (isProcessingPattern()) {\n int inputsFilled = 0;\n int outputsFilled = 0;\n for (int i = 0; i < 9; ++i) {\n if (!matrixProcessing.getStackInSlot(i).isEmpty()) {\n inputsFilled++;\n }\n }\n for (int i = 9; i < 18; ++i) {\n if (!matrixProcessing.getStackInSlot(i).isEmpty()) {\n outputsFilled++;\n }\n }\n return inputsFilled > 0 && outputsFilled > 0;\n } else {\n return !result.getStackInSlot(0).isEmpty() && isPatternAvailable();\n }\n }\n @Override\n public int getViewType() {\n return world.isRemote ? TileGrid.VIEW_TYPE.getValue() : viewType;\n }\n @Override\n public int getSortingDirection() {\n return world.isRemote ? TileGrid.SORTING_DIRECTION.getValue() : sortingDirection;\n }\n @Override\n public int getSortingType() {\n return world.isRemote ? TileGrid.SORTING_TYPE.getValue() : sortingType;\n }\n @Override\n public int getSearchBoxMode() {\n return world.isRemote ? TileGrid.SEARCH_BOX_MODE.getValue() : searchBoxMode;\n }\n @Override\n public int getSize() {\n return world.isRemote ? TileGrid.SIZE.getValue() : size;\n }\n @Override\n public int getTabSelected() {\n return world.isRemote ? TileGrid.TAB_SELECTED.getValue() : tabSelected;\n }\n @Override\n public int getTabPage() {\n return world.isRemote ? TileGrid.TAB_PAGE.getValue() : Math.min(tabPage, getTotalTabPages());\n }\n @Override\n public int getTotalTabPages() {\n return (int) Math.floor((float) Math.max(0, tabs.size() - 1) / (float) IGrid.TABS_PER_PAGE);\n }\n @Override\n public void onViewTypeChanged(int type) {\n TileDataManager.setParameter(TileGrid.VIEW_TYPE, type);\n }\n @Override\n public void onSortingTypeChanged(int type) {\n TileDataManager.setParameter(TileGrid.SORTING_TYPE, type);\n }\n @Override\n public void onSortingDirectionChanged(int direction) {\n TileDataManager.setParameter(TileGrid.SORTING_DIRECTION, direction);\n }\n @Override\n public void onSearchBoxModeChanged(int searchBoxMode) {\n TileDataManager.setParameter(TileGrid.SEARCH_BOX_MODE, searchBoxMode);\n }\n @Override\n public void onSizeChanged(int size) {\n TileDataManager.setParameter(TileGrid.SIZE, size);\n }\n @Override\n public void onTabSelectionChanged(int tab) {\n TileDataManager.setParameter(TileGrid.TAB_SELECTED, tab);\n }\n @Override\n public void onTabPageChanged(int page) {\n if (page >= 0 && page <= getTotalTabPages()) {\n TileDataManager.setParameter(TileGrid.TAB_PAGE, page);\n }\n }\n @Override\n public boolean hasConnectivityState() {\n return true;\n }\n @Override\n public void read(NBTTagCompound tag) {\n super.read(tag);\n StackUtils.readItems(matrix, 0, tag);\n StackUtils.readItems(patterns, 1, tag);\n StackUtils.readItems(filter, 2, tag);\n StackUtils.readItems(matrixProcessing, 3, tag);\n if (tag.hasKey(NBT_TAB_SELECTED)) {\n tabSelected = tag.getInteger(NBT_TAB_SELECTED);\n }\n if (tag.hasKey(NBT_TAB_PAGE)) {\n tabPage = tag.getInteger(NBT_TAB_PAGE);\n }\n }\n @Override\n public String getId() {\n return ID;\n }\n @Override\n public NBTTagCompound write(NBTTagCompound tag) {\n super.write(tag);\n StackUtils.writeItems(matrix, 0, tag);\n StackUtils.writeItems(patterns, 1, tag);\n StackUtils.writeItems(filter, 2, tag);\n StackUtils.writeItems(matrixProcessing, 3, tag);\n tag.setInteger(NBT_TAB_SELECTED, tabSelected);\n tag.setInteger(NBT_TAB_PAGE, tabPage);\n return tag;\n }\n @Override\n public NBTTagCompound writeConfiguration(NBTTagCompound tag) {\n super.writeConfiguration(tag);\n tag.setInteger(NBT_VIEW_TYPE, viewType);\n tag.setInteger(NBT_SORTING_DIRECTION, sortingDirection);\n tag.setInteger(NBT_SORTING_TYPE, sortingType);\n tag.setInteger(NBT_SEARCH_BOX_MODE, searchBoxMode);\n tag.setInteger(NBT_SIZE, size);\n tag.setBoolean(NBT_OREDICT_PATTERN, oredictPattern);\n tag.setBoolean(NBT_PROCESSING_PATTERN, processingPattern);\n return tag;\n }\n @Override\n public void readConfiguration(NBTTagCompound tag) {\n super.readConfiguration(tag);\n if (tag.hasKey(NBT_VIEW_TYPE)) {\n viewType = tag.getInteger(NBT_VIEW_TYPE);\n }\n if (tag.hasKey(NBT_SORTING_DIRECTION)) {\n sortingDirection = tag.getInteger(NBT_SORTING_DIRECTION);\n }\n if (tag.hasKey(NBT_SORTING_TYPE)) {\n sortingType = tag.getInteger(NBT_SORTING_TYPE);\n }\n if (tag.hasKey(NBT_SEARCH_BOX_MODE)) {\n searchBoxMode = tag.getInteger(NBT_SEARCH_BOX_MODE);\n }\n if (tag.hasKey(NBT_SIZE)) {\n size = tag.getInteger(NBT_SIZE);\n }\n if (tag.hasKey(NBT_OREDICT_PATTERN)) {\n oredictPattern = tag.getBoolean(NBT_OREDICT_PATTERN);\n }\n if (tag.hasKey(NBT_PROCESSING_PATTERN)) {\n processingPattern = tag.getBoolean(NBT_PROCESSING_PATTERN);\n }\n }\n @Override\n public IItemHandler getDrops() {\n switch (getType()) {\n case CRAFTING:\n return new CombinedInvWrapper(filter, new InvWrapper(matrix));\n case PATTERN:\n return new CombinedInvWrapper(filter, patterns);\n default:\n return new CombinedInvWrapper(filter);\n }\n }\n}"}}},{"rowIdx":1262,"cells":{"answer":{"kind":"string","value":"package io.cattle.platform.configitem.context.dao.impl;\nimport static io.cattle.platform.core.model.tables.HostIpAddressMapTable.*;\nimport static io.cattle.platform.core.model.tables.HostTable.*;\nimport static io.cattle.platform.core.model.tables.InstanceHostMapTable.*;\nimport static io.cattle.platform.core.model.tables.InstanceTable.*;\nimport static io.cattle.platform.core.model.tables.IpAddressNicMapTable.*;\nimport static io.cattle.platform.core.model.tables.IpAddressTable.*;\nimport static io.cattle.platform.core.model.tables.NetworkTable.*;\nimport static io.cattle.platform.core.model.tables.NicTable.*;\nimport static io.cattle.platform.core.model.tables.ServiceExposeMapTable.*;\nimport io.cattle.platform.configitem.context.dao.DnsInfoDao;\nimport io.cattle.platform.configitem.context.dao.MetaDataInfoDao;\nimport io.cattle.platform.configitem.context.data.metadata.common.ContainerMetaData;\nimport io.cattle.platform.configitem.context.data.metadata.common.HostMetaData;\nimport io.cattle.platform.configitem.context.data.metadata.common.NetworkMetaData;\nimport io.cattle.platform.core.constants.CommonStatesConstants;\nimport io.cattle.platform.core.constants.InstanceConstants;\nimport io.cattle.platform.core.constants.IpAddressConstants;\nimport io.cattle.platform.core.constants.ServiceConstants;\nimport io.cattle.platform.core.dao.InstanceDao;\nimport io.cattle.platform.core.model.Host;\nimport io.cattle.platform.core.model.Instance;\nimport io.cattle.platform.core.model.IpAddress;\nimport io.cattle.platform.core.model.Network;\nimport io.cattle.platform.core.model.Nic;\nimport io.cattle.platform.core.model.ServiceExposeMap;\nimport io.cattle.platform.core.model.tables.HostTable;\nimport io.cattle.platform.core.model.tables.InstanceTable;\nimport io.cattle.platform.core.model.tables.IpAddressTable;\nimport io.cattle.platform.core.model.tables.NetworkTable;\nimport io.cattle.platform.core.model.tables.NicTable;\nimport io.cattle.platform.core.model.tables.ServiceExposeMapTable;\nimport io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao;\nimport io.cattle.platform.db.jooq.mapper.MultiRecordMapper;\nimport io.cattle.platform.object.util.DataAccessor;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.inject.Inject;\nimport org.jooq.JoinType;\nimport org.jooq.Record1;\nimport org.jooq.RecordHandler;\npublic class MetaDataInfoDaoImpl extends AbstractJooqDao implements MetaDataInfoDao {\n @Inject\n DnsInfoDao dnsInfoDao;\n @Inject\n InstanceDao instanceDao;\n @Override\n public List getContainersData(long accountId) {\n final Map instanceIdToHostIpMap = dnsInfoDao\n .getInstanceWithHostNetworkingToIpMap(accountId);\n final Map hostIdToHostMetadata = getHostIdToHostMetadata(accountId);\n MultiRecordMapper mapper = new MultiRecordMapper() {\n @Override\n protected ContainerMetaData map(List input) {\n ContainerMetaData data = new ContainerMetaData();\n Instance instance = (Instance) input.get(0);\n instance.setData(instanceDao.getCacheInstanceData(instance.getId()));\n ServiceExposeMap serviceMap = input.get(1) != null ? (ServiceExposeMap) input.get(1) : null;\n String serviceIndex = DataAccessor.fieldString(instance,\n InstanceConstants.FIELD_SERVICE_INSTANCE_SERVICE_INDEX);\n Host host = null;\n if (input.get(2) != null) {\n host = (Host) input.get(2);\n }\n String primaryIp = null;\n if (input.get(3) != null) {\n primaryIp = ((IpAddress) input.get(3)).getAddress();\n }\n if (instanceIdToHostIpMap != null && instanceIdToHostIpMap.containsKey(instance.getId())) {\n data.setIp(instanceIdToHostIpMap.get(instance.getId()).getAddress());\n } else {\n data.setIp(primaryIp);\n }\n if (host != null) {\n HostMetaData hostMetaData = hostIdToHostMetadata.get(host.getId());\n data.setInstanceAndHostMetadata(instance, hostMetaData);\n }\n data.setExposeMap(serviceMap);\n data.setService_index(serviceIndex);\n Nic nic = null;\n if (input.get(4) != null) {\n nic = (Nic) input.get(4);\n data.setNicInformation(nic);\n }\n Network ntwk = null;\n if (input.get(5) != null) {\n ntwk = (Network) input.get(5);\n data.setNetwork_uuid(ntwk.getUuid());\n }\n return data;\n }\n };\n InstanceTable instance = mapper.add(INSTANCE, INSTANCE.UUID, INSTANCE.NAME, INSTANCE.CREATE_INDEX, INSTANCE.HEALTH_STATE,\n INSTANCE.START_COUNT, INSTANCE.STATE, INSTANCE.EXTERNAL_ID, INSTANCE.MEMORY_RESERVATION, INSTANCE.MILLI_CPU_RESERVATION);\n ServiceExposeMapTable exposeMap = mapper.add(SERVICE_EXPOSE_MAP, SERVICE_EXPOSE_MAP.SERVICE_ID,\n SERVICE_EXPOSE_MAP.DNS_PREFIX, SERVICE_EXPOSE_MAP.UPGRADE);\n HostTable host = mapper.add(HOST, HOST.ID);\n IpAddressTable instanceIpAddress = mapper.add(IP_ADDRESS, IP_ADDRESS.ADDRESS);\n NicTable nic = mapper.add(NIC, NIC.ID, NIC.INSTANCE_ID, NIC.MAC_ADDRESS);\n NetworkTable ntwk = mapper.add(NETWORK, NETWORK.UUID);\n return create()\n .select(mapper.fields())\n .from(instance)\n .join(INSTANCE_HOST_MAP)\n .on(instance.ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID))\n .join(host)\n .on(host.ID.eq(INSTANCE_HOST_MAP.HOST_ID))\n .join(exposeMap, JoinType.LEFT_OUTER_JOIN)\n .on(exposeMap.INSTANCE_ID.eq(instance.ID))\n .join(nic)\n .on(nic.INSTANCE_ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID))\n .join(IP_ADDRESS_NIC_MAP)\n .on(IP_ADDRESS_NIC_MAP.NIC_ID.eq(nic.ID))\n .join(instanceIpAddress)\n .on(instanceIpAddress.ID.eq(IP_ADDRESS_NIC_MAP.IP_ADDRESS_ID))\n .join(ntwk)\n .on(nic.NETWORK_ID.eq(ntwk.ID))\n .where(instance.ACCOUNT_ID.eq(accountId))\n .and(instance.REMOVED.isNull())\n .and(instance.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED))\n .and(exposeMap.REMOVED.isNull())\n .and(instanceIpAddress.ROLE.eq(IpAddressConstants.ROLE_PRIMARY))\n .and(ntwk.REMOVED.isNull())\n .and((host.REMOVED.isNull()))\n .and(exposeMap.STATE.isNull().or(\n exposeMap.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED)))\n .and(exposeMap.UPGRADE.isNull().or(exposeMap.UPGRADE.eq(false)))\n .fetch().map(mapper);\n }\n @Override\n public List getPrimaryIpsOnInstanceHost(final long hostId) {\n final List ips = new ArrayList<>();\n create().select(IP_ADDRESS.ADDRESS)\n .from(IP_ADDRESS)\n .join(IP_ADDRESS_NIC_MAP)\n .on(IP_ADDRESS.ID.eq(IP_ADDRESS_NIC_MAP.IP_ADDRESS_ID))\n .join(NIC)\n .on(NIC.ID.eq(IP_ADDRESS_NIC_MAP.NIC_ID))\n .join(INSTANCE_HOST_MAP)\n .on(INSTANCE_HOST_MAP.INSTANCE_ID.eq(NIC.INSTANCE_ID))\n .where(INSTANCE_HOST_MAP.HOST_ID.eq(hostId)\n .and(NIC.REMOVED.isNull())\n .and(IP_ADDRESS_NIC_MAP.REMOVED.isNull())\n .and(IP_ADDRESS.REMOVED.isNull())\n .and(IP_ADDRESS.ROLE.eq(IpAddressConstants.ROLE_PRIMARY))\n )\n .fetchInto(new RecordHandler>() {\n @Override\n public void next(Record1 record) {\n ips.add(record.value1());\n }\n });\n return ips;\n }\n @Override\n public Map getHostIdToHostMetadata(long accountId) {\n Map toReturn = new HashMap<>();\n List hosts = getAllInstanceHostMetaData(accountId);\n for (HostMetaData host : hosts) {\n toReturn.put(host.getHostId(), host);\n }\n return toReturn;\n }\n protected List getAllInstanceHostMetaData(long accountId) {\n MultiRecordMapper mapper = new MultiRecordMapper() {\n @Override\n protected HostMetaData map(List input) {\n Host host = (Host)input.get(0);\n IpAddress hostIp = (IpAddress)input.get(1);\n HostMetaData data = new HostMetaData(hostIp.getAddress(), host);\n return data;\n }\n };\n HostTable host = mapper.add(HOST);\n IpAddressTable hostIpAddress = mapper.add(IP_ADDRESS);\n return create()\n .select(mapper.fields())\n .from(hostIpAddress)\n .join(HOST_IP_ADDRESS_MAP)\n .on(HOST_IP_ADDRESS_MAP.IP_ADDRESS_ID.eq(hostIpAddress.ID))\n .join(host)\n .on(host.ID.eq(HOST_IP_ADDRESS_MAP.HOST_ID))\n .where(host.REMOVED.isNull())\n .and(host.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED))\n .and(hostIpAddress.REMOVED.isNull())\n .and(host.ACCOUNT_ID.eq(accountId))\n .fetch().map(mapper);\n }\n @Override\n public List getInstanceHostMetaData(long accountId, long instanceId) {\n MultiRecordMapper mapper = new MultiRecordMapper() {\n @Override\n protected HostMetaData map(List input) {\n Host host = (Host) input.get(0);\n IpAddress hostIp = (IpAddress) input.get(1);\n HostMetaData data = new HostMetaData(hostIp.getAddress(), host);\n return data;\n }\n };\n HostTable host = mapper.add(HOST);\n IpAddressTable hostIpAddress = mapper.add(IP_ADDRESS);\n return create()\n .select(mapper.fields())\n .from(hostIpAddress)\n .join(HOST_IP_ADDRESS_MAP)\n .on(HOST_IP_ADDRESS_MAP.IP_ADDRESS_ID.eq(hostIpAddress.ID))\n .join(host)\n .on(host.ID.eq(HOST_IP_ADDRESS_MAP.HOST_ID))\n .join(INSTANCE_HOST_MAP)\n .on(host.ID.eq(INSTANCE_HOST_MAP.HOST_ID))\n .where(host.REMOVED.isNull())\n .and(host.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED))\n .and(INSTANCE_HOST_MAP.INSTANCE_ID.eq(instanceId))\n .and(hostIpAddress.REMOVED.isNull())\n .and(host.ACCOUNT_ID.eq(accountId))\n .fetch().map(mapper);\n }\n @Override\n public List getNetworksMetaData(long accountId) {\n MultiRecordMapper mapper = new MultiRecordMapper() {\n @Override\n protected NetworkMetaData map(List input) {\n Network ntwk = (Network) input.get(0);\n Map meta = DataAccessor.fieldMap(ntwk, ServiceConstants.FIELD_METADATA);\n NetworkMetaData data = new NetworkMetaData(ntwk.getName(), ntwk.getUuid(), meta);\n return data;\n }\n };\n NetworkTable ntwk = mapper.add(NETWORK, NETWORK.NAME, NETWORK.UUID, NETWORK.DATA);\n return create()\n .select(mapper.fields())\n .from(ntwk)\n .where(ntwk.REMOVED.isNull())\n .and(ntwk.ACCOUNT_ID.eq(accountId))\n .fetch().map(mapper);\n }\n}"}}},{"rowIdx":1263,"cells":{"answer":{"kind":"string","value":"package com.royalrangers.controller.achievement;\nimport com.dropbox.core.DbxException;\nimport com.royalrangers.dto.ResponseResult;\nimport com.royalrangers.dto.achievement.AchievementRequestDto;\nimport com.royalrangers.enums.ImageType;\nimport com.royalrangers.service.DropboxService;\nimport com.royalrangers.service.achievement.QuarterAchievementService;\nimport com.royalrangers.utils.ResponseBuilder;\nimport io.swagger.annotations.ApiOperation;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.multipart.MultipartFile;\nimport java.io.IOException;\n@Slf4j\n@RestController\n@RequestMapping(\"/achievements/quarter\")\npublic class QuarterAchievementController {\n @Autowired\n private QuarterAchievementService quarterAchievementService;\n @Autowired\n private DropboxService dropboxService;\n @GetMapping\n @ApiOperation(value = \"Get all quarter achievements\")\n public ResponseResult getAllQuarterAchievement() {\n try {\n return ResponseBuilder.success(quarterAchievementService.getAllQuarterAchievement());\n } catch (Exception ex) {\n log.error(ex.getMessage());\n return ResponseBuilder.fail(\"Failed added QuarterAchievement\");\n }\n }\n @ApiOperation(value = \"Add quarter achievement related to year achievement (upLevelId)\")\n @PostMapping\n public ResponseResult addQuarterAchievement(@RequestBody AchievementRequestDto params) {\n try {\n quarterAchievementService.addQuarterAchievement(params);\n return ResponseBuilder.success(\"Adding QuarterAchievement was a success\");\n } catch (Exception ex) {\n log.error(ex.getMessage());\n return ResponseBuilder.fail(\"Failed added QuarterAchievement\");\n }\n }\n @GetMapping(\"/{quarterId}\")\n @ApiOperation(value = \"Get quarter achievement by id\")\n public ResponseResult getQuarterAchievementById(@PathVariable Long quarterId) {\n try {\n return ResponseBuilder.success(quarterAchievementService.getQuarterAchievementById(quarterId));\n } catch (Exception ex) {\n log.error(ex.getMessage());\n return ResponseBuilder.fail(\"Failed get QuarterAchievement by id\");\n }\n }\n @DeleteMapping(\"/{quarterId}\")\n @ApiOperation(value = \"Delete quarter achievement by id\")\n public ResponseResult deleteQuarterAchievement(@PathVariable Long quarterId) {\n try {\n quarterAchievementService.deleteQuarterAchievement(quarterId);\n return ResponseBuilder.success(\"Delete QuarterAchievement was a success\");\n } catch (Exception ex) {\n log.error(ex.getMessage());\n return ResponseBuilder.fail(\"Failed deleted QuarterAchievement\");\n }\n }\n @PutMapping(\"/{quarterId}\")\n @ApiOperation(value = \"Update quarter achievement by id\")\n public ResponseResult editQuarterAchievement(@RequestBody AchievementRequestDto params, @PathVariable Long quarterId) {\n try {\n return ResponseBuilder.success(quarterAchievementService.editQuarterAchievement(params, quarterId));\n } catch (Exception ex) {\n log.error(ex.getMessage());\n return ResponseBuilder.fail(\"Failed edit QuarterAchievement\");\n }\n }\n @PostMapping(\"/logo\")\n @ApiOperation(value = \"Upload and set quarter achievement logo\")\n public ResponseResult uploadLogo(@RequestParam(\"quarterId\") Long quarterId, @RequestParam(\"file\") MultipartFile file) {\n try {\n String logoUrl = dropboxService.imageUpload(file, ImageType.QUARTER_ACHIEVEMENT_LOGO);\n quarterAchievementService.setLogoUrl(logoUrl, quarterId);\n return ResponseBuilder.success(\"LogoUrl\", logoUrl);\n } catch (IOException | DbxException e) {\n return ResponseBuilder.fail(e.getMessage());\n }\n }\n @DeleteMapping(\"/logo\")\n @ApiOperation(value = \"Delete quarter achievement logo\")\n public ResponseResult delete(@RequestParam(\"quarterId\") Long quarterId) {\n try {\n quarterAchievementService.deleteLogo(quarterId);\n return ResponseBuilder.success(\"Logo deleted.\");\n } catch (DbxException e) {\n return ResponseBuilder.fail(e.getMessage());\n }\n }\n}"}}},{"rowIdx":1264,"cells":{"answer":{"kind":"string","value":"package com.yahoo.sketches.pig.tuple;\nimport com.yahoo.memory.Memory;\nimport com.yahoo.sketches.tuple.ArrayOfDoublesSketch;\nimport com.yahoo.sketches.tuple.ArrayOfDoublesSketches;\nimport java.io.IOException;\nimport org.apache.commons.math3.stat.inference.TTest;\nimport org.apache.commons.math3.stat.StatUtils;\nimport org.apache.pig.EvalFunc;\nimport org.apache.pig.data.DataByteArray;\nimport org.apache.pig.data.Tuple;\n/**\n * Calculate p-values given two ArrayOfDoublesSketch. Each value in the sketch\n * is treated as a separate metric measurement, and a p-value will be generated\n * for each metric.\n *\n * The t-statistic is calculated as follows: t = (m1 - m2) / sqrt(var1/n1 + var2/n2)\n *\n * Degrees of freedom is approximated by Welch-Satterthwaite.\n */\npublic class ArrayOfDoublesSketchesToPValueEstimates extends EvalFunc {\n @Override\n public Tuple exec(final Tuple input) throws IOException {\n if ((input == null) || (input.size() != 2)) {\n return null;\n }\n // Get the two sketches\n final DataByteArray dbaA = (DataByteArray) input.get(0);\n final DataByteArray dbaB = (DataByteArray) input.get(1);\n final ArrayOfDoublesSketch sketchA = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dbaA.get()));\n final ArrayOfDoublesSketch sketchB = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dbaB.get()));\n // Check that the size of the arrays in the sketches are the same\n if (sketchA.getNumValues() != sketchB.getNumValues()) {\n throw new IllegalArgumentException(\"Both sketches must have the same number of values\");\n }\n // Check if either sketch is empty\n if (sketchA.isEmpty() || sketchB.isEmpty()) {\n return null;\n }\n // Check that each sketch has at least 2 values\n if (sketchA.getRetainedEntries() < 2 || sketchB.getRetainedEntries() < 2) {\n return null;\n }\n // Get the values from each sketch\n double[][] valuesA = sketchA.getValues();\n double[][] valuesB = sketchB.getValues();\n valuesA = rotateMatrix(valuesA);\n valuesB = rotateMatrix(valuesB);\n // Calculate the p-values\n double[] pValues = new double[valuesA.length];\n TTestWithSketch tTest = new TTestWithSketch();\n for (int i = 0; i < valuesA.length; i++) {\n // Do some special math to get an accurate mean from the sketches\n // Take the sum of the values, divide by theta, then divide by the\n // estimate number of records.\n double meanA = (StatUtils.sum(valuesA[i]) / sketchA.getTheta()) / sketchA.getEstimate();\n double meanB = (StatUtils.sum(valuesB[i]) / sketchB.getTheta()) / sketchB.getEstimate();\n // Variance is based only on the samples we have in the tuple sketch\n double varianceA = StatUtils.variance(valuesA[i]);\n double varianceB = StatUtils.variance(valuesB[i]);\n // Use the estimated number of uniques\n double numA = sketchA.getEstimate();\n double numB = sketchB.getEstimate();\n pValues[i] = tTest.callTTest(meanA, meanB, varianceA, varianceB, numA, numB);\n }\n return Util.doubleArrayToTuple(pValues);\n }\n /**\n * Perform a clockwise rotation the output values from the tuple sketch.\n *\n * @param m Input matrix to rotate\n * @return Rotated matrix\n */\n private static double[][] rotateMatrix(double[][] m) {\n final int width = m.length;\n final int height = m[0].length;\n double[][] result = new double[height][width];\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n result[j][width - 1 - i] = m[i][j];\n }\n }\n return result;\n }\n /**\n * This class exists to get around the protected tTest method.\n */\n private class TTestWithSketch extends TTest {\n /**\n * Call the protected tTest method.\n */\n public double callTTest(double m1, double m2, double v1, double v2, double n1, double n2) {\n return super.tTest(m1, m2, v1, v2, n1, n2);\n }\n }\n}"}}},{"rowIdx":1265,"cells":{"answer":{"kind":"string","value":"package org.phenotips.data.internal;\nimport org.phenotips.Constants;\nimport org.xwiki.component.annotation.Component;\nimport org.xwiki.model.EntityType;\nimport org.xwiki.model.reference.DocumentReference;\nimport org.xwiki.model.reference.DocumentReferenceResolver;\nimport org.xwiki.model.reference.EntityReference;\nimport org.xwiki.model.reference.EntityReferenceSerializer;\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.inject.Singleton;\nimport org.apache.commons.lang3.StringUtils;\nimport org.hibernate.HibernateException;\nimport org.hibernate.Query;\nimport org.hibernate.Session;\nimport com.xpn.xwiki.XWiki;\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.XWikiDocument;\nimport com.xpn.xwiki.objects.BaseObject;\nimport com.xpn.xwiki.objects.LargeStringProperty;\nimport com.xpn.xwiki.objects.StringProperty;\nimport com.xpn.xwiki.store.XWikiHibernateBaseStore.HibernateCallback;\nimport com.xpn.xwiki.store.XWikiHibernateStore;\nimport com.xpn.xwiki.store.migration.DataMigrationException;\nimport com.xpn.xwiki.store.migration.XWikiDBVersion;\nimport com.xpn.xwiki.store.migration.hibernate.AbstractHibernateDataMigration;\n/**\n * Migration for PhenoTips issue #1280: automatically migrate old candidate, rejected and solved genes to the new\n * unified genes data structure.\n *
      \n *
    • For each {@code InvestigationClass} object create a new {@code GeneClass} object, copying the {@code gene} and\n * {@code comments}) fields, and set the {@code status} as \"candidate\".
    • \n *
    • For each {@code RejectedGenesClass} object create a new {@code GeneClass} object, copying the {@code gene} and\n * {@code comments}) fields, and set the {@code status} as \"rejected\".
    • \n *
    • If the {@code PatientClass} has a non-empty {@code solved__gene_id} property, create a new {@code GeneClass}\n * object, copying the {@code gene} field, and set the {@code status} as \"solved\".
    • \n *
    • Successfully migrated objects are removed.
    • \n *
    \n *\n * @version $Id$\n * @since 1.3M1\n */\n@Component\n@Named(\"R71490PhenoTips#1280\")\n@Singleton\npublic class R71490PhenoTips1280DataMigration extends AbstractHibernateDataMigration implements\n HibernateCallback\n{\n private static final String GENE_NAME = \"gene\";\n private static final String COMMENTS_NAME = \"comments\";\n private static final String SOLVED_NAME = \"solved__gene_id\";\n private static final String STATUS_NAME = \"status\";\n private static final String OR = \"' or o.className = '\";\n private static final EntityReference PATIENT_CLASS = new EntityReference(\"PatientClass\", EntityType.DOCUMENT,\n Constants.CODE_SPACE_REFERENCE);\n private static final EntityReference INVESTIGATION_CLASS = new EntityReference(\"InvestigationClass\",\n EntityType.DOCUMENT,\n Constants.CODE_SPACE_REFERENCE);\n private static final EntityReference GENE_CLASS = new EntityReference(\"GeneClass\", EntityType.DOCUMENT,\n Constants.CODE_SPACE_REFERENCE);\n private static final EntityReference REJECTED_CLASS = new EntityReference(\"RejectedGenesClass\",\n EntityType.DOCUMENT,\n Constants.CODE_SPACE_REFERENCE);\n /** Resolves unprefixed document names to the current wiki. */\n @Inject\n @Named(\"current\")\n private DocumentReferenceResolver resolver;\n /** Serializes the class name without the wiki prefix, to be used in the database query. */\n @Inject\n @Named(\"compactwiki\")\n private EntityReferenceSerializer serializer;\n /** Resolves class names to the current wiki. */\n @Inject\n @Named(\"current\")\n private DocumentReferenceResolver entityResolver;\n @Override\n public String getDescription()\n {\n return \"Migrate all existing gene values to the GeneClass objects\";\n }\n @Override\n public XWikiDBVersion getVersion()\n {\n return new XWikiDBVersion(71490);\n }\n @Override\n public void hibernateMigrate() throws DataMigrationException, XWikiException\n {\n getStore().executeWrite(getXWikiContext(), this);\n }\n @Override\n public Object doInHibernate(Session session) throws HibernateException, XWikiException\n {\n XWikiContext context = getXWikiContext();\n XWiki xwiki = context.getWiki();\n DocumentReference patientClassReference = this.entityResolver.resolve(PATIENT_CLASS);\n DocumentReference investigationClassReference = this.entityResolver.resolve(INVESTIGATION_CLASS);\n DocumentReference geneClassReference = this.entityResolver.resolve(GENE_CLASS);\n DocumentReference rejectedGenesClassReference = this.entityResolver.resolve(REJECTED_CLASS);\n Query q =\n session.createQuery(\"select distinct o.name from BaseObject o where o.className = '\"\n + this.serializer.serialize(investigationClassReference) + OR\n + this.serializer.serialize(rejectedGenesClassReference) + OR\n + this.serializer.serialize(patientClassReference)\n + \"' and exists(from StringProperty p where p.id.id = o.id and p.id.name = '\"\n + SOLVED_NAME + \"' and p.value <> '')\");\n @SuppressWarnings(\"unchecked\")\n List docs = q.list();\n for (String docName : docs) {\n XWikiDocument doc = xwiki.getDocument(this.resolver.resolve(docName), context);\n List geneList = new ArrayList<>();\n migrateSolvedGenes(doc, patientClassReference, geneClassReference, context, geneList);\n migrateGenes(doc, rejectedGenesClassReference, geneClassReference, context, geneList, \"rejected\");\n migrateGenes(doc, investigationClassReference, geneClassReference, context, geneList, \"candidate\");\n doc.setComment(\"Migrate old candidate/rejected/solved genes to GeneClass objects\");\n doc.setMinorEdit(true);\n try {\n // There's a bug in XWiki which prevents saving an object in the same session that it was loaded,\n // so we must clear the session cache first.\n session.clear();\n ((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, false);\n session.flush();\n } catch (DataMigrationException e) {\n }\n }\n return null;\n }\n private void migrateSolvedGenes(XWikiDocument doc, DocumentReference patientClassReference,\n DocumentReference geneClassReference, XWikiContext context, List geneList)\n throws HibernateException, XWikiException\n {\n BaseObject patient = doc.getXObject(patientClassReference);\n StringProperty oldTarget = (StringProperty) patient.get(SOLVED_NAME);\n if (oldTarget == null) {\n return;\n }\n patient.removeField(SOLVED_NAME);\n String geneName = oldTarget.getValue();\n if (!StringUtils.isBlank(geneName)) {\n BaseObject gene = doc.newXObject(geneClassReference, context);\n gene.setStringValue(GENE_NAME, geneName);\n gene.setStringValue(STATUS_NAME, \"solved\");\n geneList.add(geneName);\n }\n }\n private void migrateGenes(XWikiDocument doc, DocumentReference oldGenesClassReference,\n DocumentReference geneClassReference, XWikiContext context, List geneList, String status)\n throws HibernateException, XWikiException\n {\n List genes = doc.getXObjects(oldGenesClassReference);\n if (genes == null || genes.isEmpty()) {\n return;\n }\n for (BaseObject gene : genes) {\n if (gene == null) {\n continue;\n }\n StringProperty oldGeneNameProp = (StringProperty) gene.get(GENE_NAME);\n if (oldGeneNameProp == null || StringUtils.isBlank(oldGeneNameProp.getValue())) {\n continue;\n }\n String geneName = oldGeneNameProp.getValue();\n LargeStringProperty oldGeneCommentsProp = (LargeStringProperty) gene.get(COMMENTS_NAME);\n String geneComments = null;\n if (oldGeneCommentsProp != null && !StringUtils.isBlank(oldGeneCommentsProp.getValue())) {\n geneComments = oldGeneCommentsProp.getValue();\n }\n // check if we already have migrated this gene\n if (!geneList.contains(geneName)) {\n BaseObject newgene = doc.newXObject(geneClassReference, context);\n newgene.setStringValue(GENE_NAME, geneName);\n newgene.setStringValue(STATUS_NAME, status);\n if (geneComments != null) {\n newgene.setLargeStringValue(COMMENTS_NAME, geneComments);\n }\n geneList.add(geneName);\n } else if (geneComments != null) {\n String commentUpend = \"\\nAutomatic migration: gene was duplicated in the \" + status + \" gene section.\";\n commentUpend += \"\\nOriginal comment: \\n\" + geneComments;\n updateComment(geneName, doc, commentUpend, geneClassReference);\n }\n }\n doc.removeXObjects(oldGenesClassReference);\n }\n private void updateComment(String geneName, XWikiDocument doc, String commentUpend,\n DocumentReference geneClassReference) throws HibernateException, XWikiException\n {\n List genes = doc.getXObjects(geneClassReference);\n for (BaseObject gene : genes) {\n if (gene == null) {\n continue;\n }\n StringProperty geneNameProp = (StringProperty) gene.get(GENE_NAME);\n if (geneNameProp != null && geneNameProp.getValue().equals(geneName)) {\n LargeStringProperty oldGeneCommentsProp = (LargeStringProperty) gene.get(COMMENTS_NAME);\n if (oldGeneCommentsProp == null) {\n gene.setLargeStringValue(COMMENTS_NAME, commentUpend);\n } else {\n gene.setLargeStringValue(COMMENTS_NAME, oldGeneCommentsProp.getValue() + commentUpend);\n }\n }\n }\n }\n}"}}},{"rowIdx":1266,"cells":{"answer":{"kind":"string","value":"package io.github.lukehutch.fastclasspathscanner.scanner;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\nimport io.github.lukehutch.fastclasspathscanner.scanner.ClasspathElement.ClasspathResource.ClasspathResourceInZipFile;\nimport io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.FileMatchProcessorWrapper;\nimport io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.FilePathTesterAndMatchProcessorWrapper;\nimport io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.ScanSpecPathMatch;\nimport io.github.lukehutch.fastclasspathscanner.utils.FastManifestParser;\nimport io.github.lukehutch.fastclasspathscanner.utils.FastPathResolver;\nimport io.github.lukehutch.fastclasspathscanner.utils.InterruptionChecker;\nimport io.github.lukehutch.fastclasspathscanner.utils.LogNode;\nimport io.github.lukehutch.fastclasspathscanner.utils.MultiMapKeyToList;\nimport io.github.lukehutch.fastclasspathscanner.utils.Recycler;\nimport io.github.lukehutch.fastclasspathscanner.utils.WorkQueue;\n/** A zip/jarfile classpath element. */\nclass ClasspathElementZip extends ClasspathElement {\n /**\n * ZipFile recycler -- creates one ZipFile per thread that wants to concurrently access this classpath element.\n */\n private Recycler zipFileRecycler;\n /** Result of parsing the manifest file for this jarfile. */\n private FastManifestParser fastManifestParser;\n /** A zip/jarfile classpath element. */\n ClasspathElementZip(final ClasspathRelativePath classpathElt, final ScanSpec scanSpec, final boolean scanFiles,\n final InterruptionChecker interruptionChecker, final WorkQueue workQueue,\n final LogNode log) {\n super(classpathElt, scanSpec, scanFiles, interruptionChecker, log);\n final File classpathEltFile;\n try {\n classpathEltFile = classpathElt.getFile();\n } catch (final IOException e) {\n if (log != null) {\n log.log(\"Exception while trying to canonicalize path \" + classpathElt.getResolvedPath(), e);\n }\n ioExceptionOnOpen = true;\n return;\n }\n zipFileRecycler = new Recycler() {\n @Override\n public ZipFile newInstance() throws IOException {\n return new ZipFile(classpathEltFile);\n }\n };\n ZipFile zipFile = null;\n try {\n try {\n zipFile = zipFileRecycler.acquire();\n } catch (final IOException e) {\n if (log != null) {\n log.log(\"Exception opening zipfile \" + classpathEltFile, e);\n }\n ioExceptionOnOpen = true;\n return;\n }\n if (!scanFiles) {\n // If not performing a scan, just get the manifest entry manually\n fastManifestParser = new FastManifestParser(zipFile, zipFile.getEntry(\"META-INF/MANIFEST.MF\"), log);\n } else {\n // Scan for path matches within jarfile, and record ZipEntry objects of matching files.\n // Will parse the manifest file if it finds it.\n final int numEntries = zipFile.size();\n fileMatches = new MultiMapKeyToList<>();\n classfileMatches = new ArrayList<>(numEntries);\n fileToLastModified = new HashMap<>();\n scanZipFile(classpathEltFile, zipFile, log);\n }\n if (fastManifestParser != null && fastManifestParser.classPath != null) {\n // Get the classpath elements from the Class-Path manifest entry\n // (these are space-delimited).\n final String[] manifestClassPathElts = fastManifestParser.classPath.split(\" \");\n // Class-Path entries in the manifest file are resolved relative to\n // the dir the manifest's jarfile is contaiin. Get the parent path.\n final String pathOfContainingDir = FastPathResolver.resolve(classpathEltFile.getParent());\n // Create child classpath elements from Class-Path entry\n childClasspathElts = new ArrayList<>(manifestClassPathElts.length);\n for (int i = 0; i < manifestClassPathElts.length; i++) {\n final String manifestClassPathElt = manifestClassPathElts[i];\n if (!manifestClassPathElt.isEmpty()) {\n ClasspathRelativePath childRelativePath = new ClasspathRelativePath(pathOfContainingDir,\n manifestClassPathElt);\n childClasspathElts.add(childRelativePath);\n if (log != null) {\n log.log(\"Found Class-Path entry in manifest: \" + manifestClassPathElt + \" -> \"\n + childRelativePath);\n }\n }\n }\n // Schedule child classpath elements for scanning\n workQueue.addWorkUnits(childClasspathElts);\n }\n } finally {\n zipFileRecycler.release(zipFile);\n }\n }\n /** Scan a zipfile for file path patterns matching the scan spec. */\n private void scanZipFile(final File zipFileFile, final ZipFile zipFile, final LogNode log) {\n String prevParentRelativePath = null;\n ScanSpecPathMatch prevParentMatchStatus = null;\n int entryIdx = 0;\n for (final Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {\n if ((entryIdx++ & 0x3ff) == 0) {\n if (interruptionChecker.checkAndReturn()) {\n return;\n }\n }\n final ZipEntry zipEntry = entries.nextElement();\n String relativePath = zipEntry.getName();\n if (relativePath.startsWith(\"/\")) {\n // Shouldn't happen with the standard Java zipfile implementation (but just to be safe)\n relativePath = relativePath.substring(1);\n }\n // Ignore directory entries, they are not needed\n final boolean isDir = zipEntry.isDirectory();\n if (isDir) {\n continue;\n }\n // Get match status of the parent directory if this zipentry file's relative path\n // (or reuse the last match status for speed, if the directory name hasn't changed).\n final int lastSlashIdx = relativePath.lastIndexOf(\"/\");\n final String parentRelativePath = lastSlashIdx < 0 ? \"/\" : relativePath.substring(0, lastSlashIdx + 1);\n final boolean parentRelativePathChanged = !parentRelativePath.equals(prevParentRelativePath);\n final ScanSpecPathMatch parentMatchStatus =\n prevParentRelativePath == null || parentRelativePathChanged\n ? scanSpec.pathWhitelistMatchStatus(parentRelativePath) : prevParentMatchStatus;\n prevParentRelativePath = parentRelativePath;\n prevParentMatchStatus = parentMatchStatus;\n // Store entry for manifest file, if present, so that the entry doesn't have to be looked up by name\n if (relativePath.equalsIgnoreCase(\"META-INF/MANIFEST.MF\")) {\n if (log != null) {\n log.log(\"Found manifest file: \" + relativePath);\n }\n fastManifestParser = new FastManifestParser(zipFile, zipEntry, log);\n }\n // Class can only be scanned if it's within a whitelisted path subtree, or if it is a classfile\n // that has been specifically-whitelisted\n if (parentMatchStatus != ScanSpecPathMatch.WITHIN_WHITELISTED_PATH\n && (parentMatchStatus != ScanSpecPathMatch.AT_WHITELISTED_CLASS_PACKAGE\n || !scanSpec.isSpecificallyWhitelistedClass(relativePath))) {\n continue;\n }\n if (log != null) {\n log.log(\"Found whitelisted file in jarfile: \" + relativePath);\n }\n // Store relative paths of any classfiles encountered\n if (ClasspathRelativePath.isClassfile(relativePath)) {\n classfileMatches.add(new ClasspathResourceInZipFile(zipFileFile, relativePath, zipEntry));\n }\n // Match file paths against path patterns\n for (final FilePathTesterAndMatchProcessorWrapper fileMatcher :\n scanSpec.getFilePathTestersAndMatchProcessorWrappers()) {\n if (fileMatcher.filePathMatches(zipFileFile, relativePath, log)) {\n // File's relative path matches.\n // Don't use the last modified time from the individual zipEntry objects,\n // we use the last modified time for the zipfile itself instead.\n fileMatches.put(fileMatcher.fileMatchProcessorWrapper,\n new ClasspathResourceInZipFile(zipFileFile, relativePath, zipEntry));\n }\n }\n }\n fileToLastModified.put(zipFileFile, zipFileFile.lastModified());\n }\n /**\n * Open an input stream and call a FileMatchProcessor on a specific whitelisted match found within this zipfile.\n */\n @Override\n protected void openInputStreamAndProcessFileMatch(final ClasspathResource fileMatchResource,\n final FileMatchProcessorWrapper fileMatchProcessorWrapper) throws IOException {\n if (!ioExceptionOnOpen) {\n // Open InputStream on relative path within zipfile\n ZipFile zipFile = null;\n try {\n zipFile = zipFileRecycler.acquire();\n final ZipEntry zipEntry = ((ClasspathResourceInZipFile) fileMatchResource).zipEntry;\n try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {\n // Run FileMatcher\n fileMatchProcessorWrapper.processMatch(fileMatchResource.classpathEltFile,\n fileMatchResource.relativePath, inputStream, zipEntry.getSize());\n }\n } finally {\n zipFileRecycler.release(zipFile);\n }\n }\n }\n /** Open an input stream and parse a specific classfile found within this zipfile. */\n @Override\n protected void openInputStreamAndParseClassfile(final ClasspathResource classfileResource,\n final ClassfileBinaryParser classfileBinaryParser, final ScanSpec scanSpec,\n final ConcurrentHashMap stringInternMap,\n final ConcurrentLinkedQueue classInfoUnlinked, final LogNode log)\n throws InterruptedException, IOException {\n if (!ioExceptionOnOpen) {\n ZipFile zipFile = null;\n try {\n zipFile = zipFileRecycler.acquire();\n final ZipEntry zipEntry = ((ClasspathResourceInZipFile) classfileResource).zipEntry;\n try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {\n // Parse classpath binary format, creating a ClassInfoUnlinked object\n final ClassInfoUnlinked thisClassInfoUnlinked = classfileBinaryParser\n .readClassInfoFromClassfileHeader(classfileResource.relativePath, inputStream, scanSpec,\n stringInternMap, log);\n // If class was successfully read, output new ClassInfoUnlinked object\n if (thisClassInfoUnlinked != null) {\n classInfoUnlinked.add(thisClassInfoUnlinked);\n thisClassInfoUnlinked.logTo(log);\n }\n }\n } finally {\n zipFileRecycler.release(zipFile);\n }\n }\n }\n /** Close all open ZipFiles. */\n @Override\n public void close() {\n if (zipFileRecycler != null) {\n zipFileRecycler.close();\n }\n }\n}"}}},{"rowIdx":1267,"cells":{"answer":{"kind":"string","value":"package org.jboss.as.controller.remote;\nimport static java.security.AccessController.doPrivileged;\nimport static org.jboss.as.controller.logging.ControllerLogger.MGMT_OP_LOGGER;\nimport java.security.PrivilegedAction;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.LinkedBlockingDeque;\nimport java.util.concurrent.RejectedExecutionException;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\nimport org.jboss.as.controller.ModelController;\nimport org.jboss.as.protocol.mgmt.support.ManagementChannelInitialization;\nimport org.jboss.msc.service.Service;\nimport org.jboss.msc.service.ServiceName;\nimport org.jboss.msc.service.StartContext;\nimport org.jboss.msc.service.StartException;\nimport org.jboss.msc.service.StopContext;\nimport org.jboss.msc.value.InjectedValue;\nimport org.jboss.threads.EnhancedQueueExecutor;\nimport org.jboss.threads.JBossThreadFactory;\n/**\n * Service used to create operation handlers per incoming channel\n *\n * @author Kabir Khan\n */\npublic abstract class AbstractModelControllerOperationHandlerFactoryService implements Service, ManagementChannelInitialization {\n public static final ServiceName OPERATION_HANDLER_NAME_SUFFIX = ServiceName.of(\"operation\", \"handler\");\n // The defaults if no executor was defined\n private static final int WORK_QUEUE_SIZE = 512;\n private static final int POOL_CORE_SIZE = 4;\n private static final int POOL_MAX_SIZE = 4;\n private final InjectedValue modelControllerValue = new InjectedValue();\n private final InjectedValue executor = new InjectedValue();\n private final InjectedValue scheduledExecutor = new InjectedValue<>();\n private ResponseAttachmentInputStreamSupport responseAttachmentSupport;\n private ExecutorService clientRequestExecutor;\n /**\n * Use to inject the model controller that will be the target of the operations\n *\n * @return the injected value holder\n */\n public InjectedValue getModelControllerInjector() {\n return modelControllerValue;\n }\n public InjectedValue getExecutorInjector() {\n return executor;\n }\n public InjectedValue getScheduledExecutorInjector() {\n return scheduledExecutor;\n }\n /** {@inheritDoc} */\n @Override\n public synchronized void start(StartContext context) throws StartException {\n MGMT_OP_LOGGER.debugf(\"Starting operation handler service %s\", context.getController().getName());\n responseAttachmentSupport = new ResponseAttachmentInputStreamSupport(scheduledExecutor.getValue());\n final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction() {\n public JBossThreadFactory run() {\n return new JBossThreadFactory(new ThreadGroup(\"management-handler-thread\"), Boolean.FALSE, null, \"%G - %t\", null, null);\n }\n });\n if (EnhancedQueueExecutor.DISABLE_HINT) {\n ThreadPoolExecutor executor = new ThreadPoolExecutor(POOL_CORE_SIZE, POOL_MAX_SIZE,\n 600L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(WORK_QUEUE_SIZE),\n threadFactory);\n // Allow the core threads to time out as well\n executor.allowCoreThreadTimeOut(true);\n this.clientRequestExecutor = executor;\n } else {\n this.clientRequestExecutor = new EnhancedQueueExecutor.Builder()\n .setCorePoolSize(POOL_CORE_SIZE)\n .setMaximumPoolSize(POOL_MAX_SIZE)\n .setKeepAliveTime(600L, TimeUnit.SECONDS)\n .setMaximumQueueSize(WORK_QUEUE_SIZE)\n .setThreadFactory(threadFactory)\n .allowCoreThreadTimeOut(true)\n .build();\n }\n }\n /** {@inheritDoc} */\n @Override\n public synchronized void stop(final StopContext stopContext) {\n final ExecutorService executorService = executor.getValue();\n final Runnable task = new Runnable() {\n @Override\n public void run() {\n try {\n responseAttachmentSupport.shutdown();\n // Shut down new requests to the client request executor,\n // but don't mess with currently running tasks\n clientRequestExecutor.shutdown();\n } finally {\n stopContext.complete();\n }\n }\n };\n try {\n executorService.execute(task);\n } catch (RejectedExecutionException e) {\n task.run();\n } finally {\n stopContext.asynchronous();\n }\n }\n /** {@inheritDoc} */\n @Override\n public synchronized AbstractModelControllerOperationHandlerFactoryService getValue() throws IllegalStateException {\n return this;\n }\n protected ModelController getController() {\n return modelControllerValue.getValue();\n }\n protected ExecutorService getExecutor() {\n return executor.getValue();\n }\n protected ResponseAttachmentInputStreamSupport getResponseAttachmentSupport() {\n return responseAttachmentSupport;\n }\n protected final ExecutorService getClientRequestExecutor() {\n return clientRequestExecutor;\n }\n}"}}},{"rowIdx":1268,"cells":{"answer":{"kind":"string","value":"package io.github.thatsmusic99.headsplus.commands.maincommand;\nimport io.github.thatsmusic99.headsplus.HeadsPlus;\nimport io.github.thatsmusic99.headsplus.api.HPPlayer;\nimport io.github.thatsmusic99.headsplus.commands.CommandInfo;\nimport io.github.thatsmusic99.headsplus.commands.IHeadsPlusCommand;\nimport io.github.thatsmusic99.headsplus.config.ConfigTextMenus;\nimport io.github.thatsmusic99.headsplus.config.HeadsPlusMessagesManager;\nimport io.github.thatsmusic99.headsplus.util.HPUtils;\nimport org.bukkit.Bukkit;\nimport org.bukkit.OfflinePlayer;\nimport org.bukkit.command.Command;\nimport org.bukkit.command.CommandSender;\nimport org.bukkit.entity.Player;\nimport org.bukkit.util.StringUtil;\nimport org.jetbrains.annotations.NotNull;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;\n@CommandInfo(\n commandname = \"profile\",\n permission = \"headsplus.maincommand.profile\",\n maincommand = true,\n usage = \"/hp profile [Player]\",\n descriptionPath = \"descriptions.hp.profile\"\n)\npublic class ProfileCommand implements IHeadsPlusCommand {\n private String prof(OfflinePlayer p, CommandSender sender) throws SQLException {\n try {\n HPPlayer pl = HPPlayer.getHPPlayer(p);\n return ConfigTextMenus.ProfileTranslator.translate(pl, sender);\n } catch (NullPointerException ex) {\n ex.printStackTrace();\n return HeadsPlusMessagesManager.get().getString(\"commands.errors.no-data\", sender);\n }\n }\n @Override\n public boolean fire(String[] args, CommandSender cs) {\n String name = cs.getName();\n if (args.length != 1) {\n name = args[1];\n }\n HPUtils.getOfflinePlayer(name).thenAccept(player -> {\n try {\n if (cs instanceof Player) {\n if (cs.getName().equalsIgnoreCase(player.getName())) {\n cs.sendMessage(prof(player, cs));\n } else {\n if (cs.hasPermission(\"headsplus.maincommand.profile.others\")) {\n cs.sendMessage(prof(player, cs));\n } else {\n HeadsPlusMessagesManager.get().sendMessage(\"commands.errors.no-perm\", cs);\n }\n }\n } else {\n if (cs.getName().equalsIgnoreCase(player.getName())) {\n // Not a player\n cs.sendMessage(HeadsPlusMessagesManager.get().getString(\"commands.profile.cant-view-data\"));\n } else {\n cs.sendMessage(prof(player, cs));\n }\n }\n } catch (SQLException e) {\n DebugPrint.createReport(e, \"Subcommand (profile)\", true, cs);\n }\n });\n return true;\n }\n @Override\n public boolean shouldEnable() {\n return true;\n }\n @Override\n public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {\n List results = new ArrayList<>();\n if (args.length == 2) {\n StringUtil.copyPartialMatches(args[1], IHeadsPlusCommand.getPlayers(sender), results);\n }\n return results;\n }\n}"}}},{"rowIdx":1269,"cells":{"answer":{"kind":"string","value":"package net.sf.taverna.t2.workbench.reference.config;\nimport java.util.HashMap;\nimport java.util.Map;\nimport net.sf.taverna.t2.workbench.configuration.AbstractConfigurable;\n/**\n * Configuration for the reference service and provenance.\n *\n * @author David Withers\n * @author Stuart Owen\n */\npublic class DataManagementConfiguration extends AbstractConfigurable {\n public static final String IN_MEMORY = \"in_memory\";\n public static final String ENABLE_PROVENANCE = \"provenance\";\n public static final String CONNECTOR_TYPE = \"connector\";\n public static final String PORT = \"port\";\n public static final String CURRENT_PORT = \"current_port\";\n public static final String REFERENCE_SERVICE_CONTEXT = \"referenceService.context\";\n public static final String IN_MEMORY_CONTEXT = \"inMemoryReferenceServiceContext.xml\";\n public static final String HIBERNATE_CONTEXT = \"hibernateReferenceServiceContext.xml\";\n public static final String HIBERNATE_DIALECT = \"dialect\";\n public static final String START_INTERNAL_DERBY = \"start_derby\";\n public static final String POOL_MAX_ACTIVE = \"pool_max_active\";\n public static final String POOL_MIN_IDLE = \"pool_min_idle\";\n public static final String POOL_MAX_IDLE = \"pool_max_idle\";\n public static final String DRIVER_CLASS_NAME = \"driver\";\n public static final String JDBC_URI = \"jdbcuri\";\n public static final String USERNAME = \"username\";\n public static final String PASSWORD = \"password\";\n //FIXME: these should me just mysql & derby - but build & dependency issues is causing the provenance to expect these values:\n public static final String CONNECTOR_MYSQL=\"mysql\";\n public static final String CONNECTOR_DERBY=\"derby\";\n public static final String JNDI_NAME = \"jdbc/taverna\";\n private Map defaultPropertyMap;\n private static DataManagementConfiguration instance;\n public static DataManagementConfiguration getInstance() {\n if (instance == null) {\n instance = new DataManagementConfiguration();\n if (instance.getStartInternalDerbyServer()) {\n DataManagementHelper.startDerbyNetworkServer();\n }\n DataManagementHelper.setupDataSource();\n }\n return instance;\n }\n public String getDatabaseContext() {\n if (getProperty(IN_MEMORY).equalsIgnoreCase(\"true\")) {\n return IN_MEMORY_CONTEXT;\n } else {\n return HIBERNATE_CONTEXT;\n }\n }\n public String getDriverClassName() {\n return getProperty(DRIVER_CLASS_NAME);\n }\n public boolean isProvenanceEnabled() {\n return getProperty(ENABLE_PROVENANCE).equalsIgnoreCase(\"true\");\n }\n public boolean getStartInternalDerbyServer() {\n return getProperty(START_INTERNAL_DERBY).equalsIgnoreCase(\"true\");\n }\n public int getPort() {\n return Integer.valueOf(getProperty(PORT));\n }\n public void setCurrentPort(int port) {\n setProperty(CURRENT_PORT, String.valueOf(port));\n }\n public int getCurrentPort() {\n return Integer.valueOf(getProperty(CURRENT_PORT));\n }\n public int getPoolMaxActive() {\n return Integer.valueOf(getProperty(POOL_MAX_ACTIVE));\n }\n public int getPoolMinIdle() {\n return Integer.valueOf(getProperty(POOL_MIN_IDLE));\n }\n public int getPoolMaxIdle() {\n return Integer.valueOf(getProperty(POOL_MAX_IDLE));\n }\n private DataManagementConfiguration() {\n }\n public String getCategory() {\n return \"general\";\n }\n public Map getDefaultPropertyMap() {\n if (defaultPropertyMap == null) {\n defaultPropertyMap = new HashMap();\n defaultPropertyMap.put(IN_MEMORY, \"true\");\n defaultPropertyMap.put(ENABLE_PROVENANCE, \"true\");\n defaultPropertyMap.put(PORT, \"1527\");\n //defaultPropertyMap.put(DRIVER_CLASS_NAME, \"org.apache.derby.jdbc.ClientDriver\");\n defaultPropertyMap.put(DRIVER_CLASS_NAME, \"org.apache.derby.jdbc.EmbeddedDriver\");\n defaultPropertyMap.put(HIBERNATE_DIALECT, \"org.hibernate.dialect.DerbyDialect\");\n defaultPropertyMap.put(POOL_MAX_ACTIVE, \"50\");\n defaultPropertyMap.put(POOL_MAX_IDLE, \"50\");\n defaultPropertyMap.put(POOL_MIN_IDLE, \"10\");\n defaultPropertyMap.put(USERNAME,\"\");\n defaultPropertyMap.put(PASSWORD,\"\");\n defaultPropertyMap.put(JDBC_URI,\"jdbc:derby:t2-database;create=true;upgrade=true\");\n defaultPropertyMap.put(START_INTERNAL_DERBY, \"false\");\n defaultPropertyMap.put(CONNECTOR_TYPE,CONNECTOR_DERBY);\n }\n return defaultPropertyMap;\n }\n public String getHibernateDialect() {\n return getProperty(HIBERNATE_DIALECT);\n }\n public String getDisplayName() {\n return \"Data and provenance\";\n }\n public String getFilePrefix() {\n return \"DataAndProvenance\";\n }\n public String getUUID() {\n return \"6BD3F5C1-C68D-4893-8D9B-2F46FA1DDB19\";\n }\n public String getConnectorType() {\n return getProperty(CONNECTOR_TYPE);\n }\n public String getJDBCUri() {\n if (CONNECTOR_DERBY.equals(getConnectorType()) && getStartInternalDerbyServer()) {\n return \"jdbc:derby://localhost:\" + getCurrentPort() + \"/t2-database;create=true;upgrade=true\";\n }\n else {\n return getProperty(JDBC_URI);\n }\n }\n public String getUsername() {\n return getProperty(USERNAME);\n }\n public String getPassword() {\n return getProperty(PASSWORD);\n }\n}"}}},{"rowIdx":1270,"cells":{"answer":{"kind":"string","value":"package net.finmath.montecarlo.assetderivativevaluation;\nimport java.time.LocalDateTime;\nimport java.util.HashMap;\nimport java.util.Map;\nimport net.finmath.exception.CalculationException;\nimport net.finmath.montecarlo.IndependentIncrements;\nimport net.finmath.montecarlo.model.ProcessModel;\nimport net.finmath.montecarlo.process.EulerSchemeFromProcessModel;\nimport net.finmath.montecarlo.process.MonteCarloProcess;\nimport net.finmath.stochastic.RandomVariable;\nimport net.finmath.time.TimeDiscretization;\n/**\n * This class glues together an AbstractProcessModel and a Monte-Carlo implementation of a MonteCarloProcessFromProcessModel\n * and implements AssetModelMonteCarloSimulationModel.\n *\n * The model is specified via the object implementing ProcessModel.\n *\n * @author Christian Fries\n * @see net.finmath.montecarlo.process.MonteCarloProcess The interface for numerical schemes.\n * @see net.finmath.montecarlo.model.ProcessModel The interface for models provinding parameters to numerical schemes.\n * @version 1.0\n */\npublic class MonteCarloAssetModel implements AssetModelMonteCarloSimulationModel {\n private final ProcessModel model;\n private final MonteCarloProcess process;\n /**\n * Create a Monte-Carlo simulation using given process discretization scheme.\n *\n * @param process The numerical scheme to be used.\n */\n public MonteCarloAssetModel(final MonteCarloProcess process) {\n super();\n this.model = process.getModel();\n this.process = process;\n }\n /**\n * Create a Monte-Carlo simulation using given process discretization scheme.\n *\n * @param model The model to be used.\n * @param process The numerical scheme to be used.\n */\n public MonteCarloAssetModel(\n final ProcessModel model,\n final MonteCarloProcess process) {\n super();\n this.model = model;\n this.process = process;\n }\n public MonteCarloAssetModel(ProcessModel model, IndependentIncrements stochasticDriver) {\n super();\n this.model = model;\n this.process = new EulerSchemeFromProcessModel(model, stochasticDriver);\n }\n @Override\n public RandomVariable getAssetValue(final double time, final int assetIndex) throws CalculationException {\n int timeIndex = getTimeIndex(time);\n if(timeIndex < 0) {\n throw new IllegalArgumentException(\"The model does not provide an interpolation of simulation time (time given was \" + time + \").\");\n }\n return getAssetValue(timeIndex, assetIndex);\n }\n @Override\n public RandomVariable getAssetValue(final int timeIndex, final int assetIndex) throws CalculationException {\n return process.getProcessValue(timeIndex, assetIndex);\n }\n @Override\n public RandomVariable getNumeraire(final int timeIndex) throws CalculationException {\n final double time = getTime(timeIndex);\n // TODO Add caching of the numerare here!\n return model.getNumeraire(process, time);\n }\n @Override\n public RandomVariable getNumeraire(final double time) throws CalculationException {\n // TODO Add caching of the numerare here!\n return model.getNumeraire(process, time);\n }\n @Override\n public RandomVariable getMonteCarloWeights(final double time) throws CalculationException {\n return getMonteCarloWeights(getTimeIndex(time));\n }\n @Override\n public int getNumberOfAssets() {\n return 1;\n }\n @Override\n public AssetModelMonteCarloSimulationModel getCloneWithModifiedData(final Map dataModified) throws CalculationException {\n final ProcessModel newModel = model.getCloneWithModifiedData(dataModified);\n MonteCarloProcess newProcess;\n try {\n final Map dataModifiedForProcess = new HashMap();\n dataModifiedForProcess.putAll(dataModified);\n if(!dataModifiedForProcess.containsKey(\"model\")) {\n dataModifiedForProcess.put(\"model\", newModel);\n }\n newProcess = process.getCloneWithModifiedData(dataModifiedForProcess);\n }\n catch(final UnsupportedOperationException e) {\n newProcess = process;\n }\n // In the case where the model has changed we need a new process anyway\n if(newModel != model && newProcess == process) {\n newProcess = process.getCloneWithModifiedModel(newModel);\n }\n return new MonteCarloAssetModel(newModel, newProcess);\n }\n /**\n * The method is not implemented. Instead call getCloneWithModifiedData on the model\n * an create a new process from it.\n *\n * @param seed The new seed.\n */\n @Override\n @Deprecated\n public AssetModelMonteCarloSimulationModel getCloneWithModifiedSeed(final int seed) {\n throw new UnsupportedOperationException(\"Method not implemented\");\n }\n @Override\n public int getNumberOfPaths() {\n return process.getNumberOfPaths();\n }\n @Override\n public LocalDateTime getReferenceDate() {\n return model.getReferenceDate();\n }\n @Override\n public TimeDiscretization getTimeDiscretization() {\n return process.getTimeDiscretization();\n }\n @Override\n public double getTime(final int timeIndex) {\n return process.getTime(timeIndex);\n }\n @Override\n public int getTimeIndex(final double time) {\n return process.getTimeIndex(time);\n }\n @Override\n public RandomVariable getRandomVariableForConstant(final double value) {\n return model.getRandomVariableForConstant(value);\n }\n @Override\n public RandomVariable getMonteCarloWeights(final int timeIndex) throws CalculationException {\n return process.getMonteCarloWeights(timeIndex);\n }\n /**\n * Returns the {@link ProcessModel} used for this Monte-Carlo simulation.\n *\n * @return the model\n */\n public ProcessModel getModel() {\n return model;\n }\n /**\n * Returns the {@link MonteCarloProcess} used for this Monte-Carlo simulation.\n *\n * @return the process\n */\n public MonteCarloProcess getProcess() {\n return process;\n }\n @Override\n public String toString() {\n return this.getClass().getSimpleName() + \" [model=\" + model + \"]\";\n }\n}"}}},{"rowIdx":1271,"cells":{"answer":{"kind":"string","value":"package org.hisp.dhis.dxf2.metadata;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.hisp.dhis.common.IdentifiableObject;\nimport org.hisp.dhis.common.SetMap;\nimport org.hisp.dhis.commons.timer.SystemTimer;\nimport org.hisp.dhis.commons.timer.Timer;\nimport org.hisp.dhis.dataelement.DataElement;\nimport org.hisp.dhis.dataelement.DataElementCategory;\nimport org.hisp.dhis.dataelement.DataElementCategoryCombo;\nimport org.hisp.dhis.dataelement.DataElementCategoryOption;\nimport org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;\nimport org.hisp.dhis.dataelement.DataElementOperand;\nimport org.hisp.dhis.dataentryform.DataEntryForm;\nimport org.hisp.dhis.dataset.DataSet;\nimport org.hisp.dhis.dataset.DataSetElement;\nimport org.hisp.dhis.dataset.Section;\nimport org.hisp.dhis.dxf2.common.OrderParams;\nimport org.hisp.dhis.fieldfilter.FieldFilterService;\nimport org.hisp.dhis.indicator.Indicator;\nimport org.hisp.dhis.indicator.IndicatorType;\nimport org.hisp.dhis.legend.Legend;\nimport org.hisp.dhis.legend.LegendSet;\nimport org.hisp.dhis.node.NodeUtils;\nimport org.hisp.dhis.node.types.ComplexNode;\nimport org.hisp.dhis.node.types.RootNode;\nimport org.hisp.dhis.node.types.SimpleNode;\nimport org.hisp.dhis.option.Option;\nimport org.hisp.dhis.option.OptionSet;\nimport org.hisp.dhis.program.Program;\nimport org.hisp.dhis.program.ProgramIndicator;\nimport org.hisp.dhis.program.ProgramStage;\nimport org.hisp.dhis.program.ProgramStageDataElement;\nimport org.hisp.dhis.program.ProgramStageSection;\nimport org.hisp.dhis.program.ProgramTrackedEntityAttribute;\nimport org.hisp.dhis.programrule.ProgramRule;\nimport org.hisp.dhis.programrule.ProgramRuleAction;\nimport org.hisp.dhis.programrule.ProgramRuleService;\nimport org.hisp.dhis.programrule.ProgramRuleVariable;\nimport org.hisp.dhis.programrule.ProgramRuleVariableService;\nimport org.hisp.dhis.query.Query;\nimport org.hisp.dhis.query.QueryService;\nimport org.hisp.dhis.schema.Schema;\nimport org.hisp.dhis.schema.SchemaService;\nimport org.hisp.dhis.system.SystemInfo;\nimport org.hisp.dhis.system.SystemService;\nimport org.hisp.dhis.trackedentity.TrackedEntity;\nimport org.hisp.dhis.trackedentity.TrackedEntityAttribute;\nimport org.hisp.dhis.user.CurrentUserService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n/**\n * @author Morten Olav Hansen \n */\n@Component\npublic class DefaultMetadataExportService implements MetadataExportService\n{\n private static final Log log = LogFactory.getLog( MetadataExportService.class );\n @Autowired\n private SchemaService schemaService;\n @Autowired\n private QueryService queryService;\n @Autowired\n private FieldFilterService fieldFilterService;\n @Autowired\n private CurrentUserService currentUserService;\n @Autowired\n private ProgramRuleService programRuleService;\n @Autowired\n private ProgramRuleVariableService programRuleVariableService;\n @Autowired\n private SystemService systemService;\n @Override\n @SuppressWarnings( \"unchecked\" )\n public Map, List> getMetadata( MetadataExportParams params )\n {\n Timer timer = new SystemTimer().start();\n Map, List> metadata = new HashMap<>();\n if ( params.getUser() == null )\n {\n params.setUser( currentUserService.getCurrentUser() );\n }\n if ( params.getClasses().isEmpty() )\n {\n schemaService.getMetadataSchemas().stream().filter( Schema::isIdentifiableObject )\n .forEach( schema -> params.getClasses().add( (Class) schema.getKlass() ) );\n }\n log.info( \"(\" + params.getUsername() + \") Export:Start\" );\n for ( Class klass : params.getClasses() )\n {\n Query query;\n if ( params.getQuery( klass ) != null )\n {\n query = params.getQuery( klass );\n }\n else\n {\n OrderParams orderParams = new OrderParams( Sets.newHashSet( params.getDefaultOrder() ) );\n query = queryService.getQueryFromUrl( klass, params.getDefaultFilter(), orderParams.getOrders( schemaService.getDynamicSchema( klass ) ) );\n }\n if ( query.getUser() == null )\n {\n query.setUser( params.getUser() );\n }\n query.setDefaultOrder();\n List objects = queryService.query( query );\n if ( !objects.isEmpty() )\n {\n log.info( \"(\" + params.getUsername() + \") Exported \" + objects.size() + \" objects of type \" + klass.getSimpleName() );\n metadata.put( klass, objects );\n }\n }\n log.info( \"(\" + params.getUsername() + \") Export:Done took \" + timer.toString() );\n return metadata;\n }\n @Override\n public RootNode getMetadataAsNode( MetadataExportParams params )\n {\n RootNode rootNode = NodeUtils.createMetadata();\n SystemInfo systemInfo = systemService.getSystemInfo();\n ComplexNode system = rootNode.addChild( new ComplexNode( \"system\" ) );\n system.addChild( new SimpleNode( \"id\", systemInfo.getSystemId() ) );\n system.addChild( new SimpleNode( \"rev\", systemInfo.getRevision() ) );\n system.addChild( new SimpleNode( \"version\", systemInfo.getVersion() ) );\n system.addChild( new SimpleNode( \"date\", systemInfo.getServerDate() ) );\n Map, List> metadata = getMetadata( params );\n for ( Class klass : metadata.keySet() )\n {\n rootNode.addChild( fieldFilterService.filter( klass, metadata.get( klass ), params.getFields( klass ) ) );\n }\n return rootNode;\n }\n @Override\n public void validate( MetadataExportParams params )\n {\n }\n @Override\n @SuppressWarnings( \"unchecked\" )\n public MetadataExportParams getParamsFromMap( Map> parameters )\n {\n MetadataExportParams params = new MetadataExportParams();\n Map, Map>> map = new HashMap<>();\n if ( parameters.containsKey( \"fields\" ) )\n {\n params.setDefaultFields( parameters.get( \"fields\" ) );\n parameters.remove( \"fields\" );\n }\n if ( parameters.containsKey( \"filter\" ) )\n {\n params.setDefaultFilter( parameters.get( \"filter\" ) );\n parameters.remove( \"filter\" );\n }\n if ( parameters.containsKey( \"order\" ) )\n {\n params.setDefaultOrder( parameters.get( \"order\" ) );\n parameters.remove( \"order\" );\n }\n for ( String parameterKey : parameters.keySet() )\n {\n String[] parameter = parameterKey.split( \":\" );\n Schema schema = schemaService.getSchemaByPluralName( parameter[0] );\n if ( schema == null || !schema.isIdentifiableObject() )\n {\n continue;\n }\n Class klass = (Class) schema.getKlass();\n // class is enabled if value = true, or fields/filter/order is present\n if ( \"true\".equalsIgnoreCase( parameters.get( parameterKey ).get( 0 ) ) || (parameter.length > 1 && (\"fields\".equalsIgnoreCase( parameter[1] )\n || \"filter\".equalsIgnoreCase( parameter[1] ) || \"order\".equalsIgnoreCase( parameter[1] ))) )\n {\n if ( !map.containsKey( klass ) ) map.put( klass, new HashMap<>() );\n }\n else\n {\n continue;\n }\n if ( parameter.length > 1 )\n {\n if ( \"fields\".equalsIgnoreCase( parameter[1] ) )\n {\n if ( !map.get( klass ).containsKey( \"fields\" ) ) map.get( klass ).put( \"fields\", new ArrayList<>() );\n map.get( klass ).get( \"fields\" ).addAll( parameters.get( parameterKey ) );\n }\n if ( \"filter\".equalsIgnoreCase( parameter[1] ) )\n {\n if ( !map.get( klass ).containsKey( \"filter\" ) ) map.get( klass ).put( \"filter\", new ArrayList<>() );\n map.get( klass ).get( \"filter\" ).addAll( parameters.get( parameterKey ) );\n }\n if ( \"order\".equalsIgnoreCase( parameter[1] ) )\n {\n if ( !map.get( klass ).containsKey( \"order\" ) ) map.get( klass ).put( \"order\", new ArrayList<>() );\n map.get( klass ).get( \"order\" ).addAll( parameters.get( parameterKey ) );\n }\n }\n }\n map.keySet().forEach( params::addClass );\n for ( Class klass : map.keySet() )\n {\n Map> classMap = map.get( klass );\n Schema schema = schemaService.getDynamicSchema( klass );\n if ( classMap.containsKey( \"fields\" ) ) params.addFields( klass, classMap.get( \"fields\" ) );\n if ( classMap.containsKey( \"filter\" ) && classMap.containsKey( \"order\" ) )\n {\n OrderParams orderParams = new OrderParams( Sets.newHashSet( classMap.get( \"order\" ) ) );\n Query query = queryService.getQueryFromUrl( klass, classMap.get( \"filter\" ), orderParams.getOrders( schema ) );\n query.setDefaultOrder();\n params.addQuery( query );\n }\n else if ( classMap.containsKey( \"filter\" ) )\n {\n Query query = queryService.getQueryFromUrl( klass, classMap.get( \"filter\" ), new ArrayList<>() );\n query.setDefaultOrder();\n params.addQuery( query );\n }\n else if ( classMap.containsKey( \"order\" ) )\n {\n OrderParams orderParams = new OrderParams();\n orderParams.setOrder( Sets.newHashSet( classMap.get( \"order\" ) ) );\n Query query = queryService.getQueryFromUrl( klass, new ArrayList<>(), orderParams.getOrders( schema ) );\n query.setDefaultOrder();\n params.addQuery( query );\n }\n }\n return params;\n }\n @Override\n public SetMap, IdentifiableObject> getMetadataWithDependencies( IdentifiableObject object )\n {\n SetMap, IdentifiableObject> metadata = new SetMap<>();\n if ( DataSet.class.isInstance( object ) ) return handleDataSet( metadata, (DataSet) object );\n if ( Program.class.isInstance( object ) ) return handleProgram( metadata, (Program) object );\n return metadata;\n }\n @Override\n public RootNode getMetadataWithDependenciesAsNode( IdentifiableObject object )\n {\n RootNode rootNode = NodeUtils.createMetadata();\n rootNode.addChild( new SimpleNode( \"date\", new Date(), true ) );\n SetMap, IdentifiableObject> metadata = getMetadataWithDependencies( object );\n for ( Class klass : metadata.keySet() )\n {\n rootNode.addChild( fieldFilterService.filter( klass, Lists.newArrayList( metadata.get( klass ) ), Lists.newArrayList( \":owner\" ) ) );\n }\n return rootNode;\n }\n // Utility Methods\n private SetMap, IdentifiableObject> handleDataSet( SetMap, IdentifiableObject> metadata, DataSet dataSet )\n {\n metadata.putValue( DataSet.class, dataSet );\n dataSet.getDataSetElements().forEach( dataSetElement -> handleDataSetElement( metadata, dataSetElement ) );\n dataSet.getSections().forEach( section -> handleSection( metadata, section ) );\n dataSet.getIndicators().forEach( indicator -> handleIndicator( metadata, indicator ) );\n handleDataEntryForm( metadata, dataSet.getDataEntryForm() );\n handleLegendSet( metadata, dataSet.getLegendSet() );\n handleCategoryCombo( metadata, dataSet.getCategoryCombo() );\n dataSet.getCompulsoryDataElementOperands().forEach( dataElementOperand -> handleDataElementOperand( metadata, dataElementOperand ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleDataElementOperand( SetMap, IdentifiableObject> metadata, DataElementOperand dataElementOperand )\n {\n if ( dataElementOperand == null ) return metadata;\n handleCategoryOptionCombo( metadata, dataElementOperand.getCategoryOptionCombo() );\n handleLegendSet( metadata, dataElementOperand.getLegendSet() );\n handleDataElement( metadata, dataElementOperand.getDataElement() );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleCategoryOptionCombo( SetMap, IdentifiableObject> metadata, DataElementCategoryOptionCombo categoryOptionCombo )\n {\n if ( categoryOptionCombo == null ) return metadata;\n metadata.putValue( DataElementCategoryOptionCombo.class, categoryOptionCombo );\n handleCategoryCombo( metadata, categoryOptionCombo.getCategoryCombo() );\n categoryOptionCombo.getCategoryOptions().forEach( categoryOption -> handleCategoryOption( metadata, categoryOption ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleCategoryCombo( SetMap, IdentifiableObject> metadata, DataElementCategoryCombo categoryCombo )\n {\n if ( categoryCombo == null ) return metadata;\n metadata.putValue( DataElementCategoryCombo.class, categoryCombo );\n categoryCombo.getCategories().forEach( category -> handleCategory( metadata, category ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleCategory( SetMap, IdentifiableObject> metadata, DataElementCategory category )\n {\n if ( category == null ) return metadata;\n metadata.putValue( DataElementCategory.class, category );\n category.getCategoryOptions().forEach( categoryOption -> handleCategoryOption( metadata, categoryOption ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleCategoryOption( SetMap, IdentifiableObject> metadata, DataElementCategoryOption categoryOption )\n {\n if ( categoryOption == null ) return metadata;\n metadata.putValue( DataElementCategoryOption.class, categoryOption );\n categoryOption.getCategoryOptionCombos().forEach( categoryOptionCombo -> handleCategoryOptionCombo( metadata, categoryOptionCombo ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleLegendSet( SetMap, IdentifiableObject> metadata, LegendSet legendSet )\n {\n if ( legendSet == null ) return metadata;\n metadata.putValue( LegendSet.class, legendSet );\n legendSet.getLegends().forEach( legend -> handleLegend( metadata, legend ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleLegend( SetMap, IdentifiableObject> metadata, Legend legend )\n {\n if ( legend == null ) return metadata;\n metadata.putValue( Legend.class, legend );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleDataEntryForm( SetMap, IdentifiableObject> metadata, DataEntryForm dataEntryForm )\n {\n if ( dataEntryForm == null ) return metadata;\n metadata.putValue( DataEntryForm.class, dataEntryForm );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleDataSetElement( SetMap, IdentifiableObject> metadata, DataSetElement dataSetElement )\n {\n if ( dataSetElement == null ) return metadata;\n metadata.putValue( DataSetElement.class, dataSetElement );\n handleDataElement( metadata, dataSetElement.getDataElement() );\n handleCategoryCombo( metadata, dataSetElement.getCategoryCombo() );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleDataElement( SetMap, IdentifiableObject> metadata, DataElement dataElement )\n {\n if ( dataElement == null ) return metadata;\n metadata.putValue( DataElement.class, dataElement );\n handleCategoryCombo( metadata, dataElement.getDataElementCategoryCombo() );\n handleOptionSet( metadata, dataElement.getOptionSet() );\n handleOptionSet( metadata, dataElement.getCommentOptionSet() );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleOptionSet( SetMap, IdentifiableObject> metadata, OptionSet optionSet )\n {\n if ( optionSet == null ) return metadata;\n metadata.putValue( OptionSet.class, optionSet );\n optionSet.getOptions().forEach( o -> handleOption( metadata, o ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleOption( SetMap, IdentifiableObject> metadata, Option option )\n {\n if ( option == null ) return metadata;\n metadata.putValue( Option.class, option );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleSection( SetMap, IdentifiableObject> metadata, Section section )\n {\n if ( section == null ) return metadata;\n metadata.putValue( Section.class, section );\n section.getGreyedFields().forEach( dataElementOperand -> handleDataElementOperand( metadata, dataElementOperand ) );\n section.getIndicators().forEach( indicator -> handleIndicator( metadata, indicator ) );\n section.getDataElements().forEach( dataElement -> handleDataElement( metadata, dataElement ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleIndicator( SetMap, IdentifiableObject> metadata, Indicator indicator )\n {\n if ( indicator == null ) return metadata;\n metadata.putValue( Indicator.class, indicator );\n handleIndicatorType( metadata, indicator.getIndicatorType() );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleIndicatorType( SetMap, IdentifiableObject> metadata, IndicatorType indicatorType )\n {\n if ( indicatorType == null ) return metadata;\n metadata.putValue( IndicatorType.class, indicatorType );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleProgram( SetMap, IdentifiableObject> metadata, Program program )\n {\n if ( program == null ) return metadata;\n metadata.putValue( Program.class, program );\n handleCategoryCombo( metadata, program.getCategoryCombo() );\n handleDataEntryForm( metadata, program.getDataEntryForm() );\n handleTrackedEntity( metadata, program.getTrackedEntity() );\n program.getProgramStages().forEach( programStage -> handleProgramStage( metadata, programStage ) );\n program.getProgramAttributes().forEach( programTrackedEntityAttribute -> handleProgramTrackedEntityAttribute( metadata, programTrackedEntityAttribute ) );\n program.getProgramIndicators().forEach( programIndicator -> handleProgramIndicator( metadata, programIndicator ) );\n List programRules = programRuleService.getProgramRule( program );\n List programRuleVariables = programRuleVariableService.getProgramRuleVariable( program );\n programRules.forEach( programRule -> handleProgramRule( metadata, programRule ) );\n programRuleVariables.forEach( programRuleVariable -> handleProgramRuleVariable( metadata, programRuleVariable ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleProgramRuleVariable( SetMap, IdentifiableObject> metadata, ProgramRuleVariable programRuleVariable )\n {\n if ( programRuleVariable == null ) return metadata;\n metadata.putValue( ProgramRuleVariable.class, programRuleVariable );\n handleTrackedEntityAttribute( metadata, programRuleVariable.getAttribute() );\n handleDataElement( metadata, programRuleVariable.getDataElement() );\n handleProgramStage( metadata, programRuleVariable.getProgramStage() );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleTrackedEntityAttribute( SetMap, IdentifiableObject> metadata, TrackedEntityAttribute trackedEntityAttribute )\n {\n if ( trackedEntityAttribute == null ) return metadata;\n metadata.putValue( TrackedEntityAttribute.class, trackedEntityAttribute );\n handleOptionSet( metadata, trackedEntityAttribute.getOptionSet() );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleProgramRule( SetMap, IdentifiableObject> metadata, ProgramRule programRule )\n {\n if ( programRule == null ) return metadata;\n metadata.putValue( ProgramRule.class, programRule );\n programRule.getProgramRuleActions().forEach( programRuleAction -> handleProgramRuleAction( metadata, programRuleAction ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleProgramRuleAction( SetMap, IdentifiableObject> metadata, ProgramRuleAction programRuleAction )\n {\n if ( programRuleAction == null ) return metadata;\n metadata.putValue( ProgramRuleAction.class, programRuleAction );\n handleDataElement( metadata, programRuleAction.getDataElement() );\n handleTrackedEntityAttribute( metadata, programRuleAction.getAttribute() );\n handleProgramIndicator( metadata, programRuleAction.getProgramIndicator() );\n handleProgramStageSection( metadata, programRuleAction.getProgramStageSection() );\n handleProgramStage( metadata, programRuleAction.getProgramStage() );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleProgramTrackedEntityAttribute( SetMap, IdentifiableObject> metadata, ProgramTrackedEntityAttribute programTrackedEntityAttribute )\n {\n if ( programTrackedEntityAttribute == null ) return metadata;\n metadata.putValue( ProgramTrackedEntityAttribute.class, programTrackedEntityAttribute );\n handleTrackedEntityAttribute( metadata, programTrackedEntityAttribute.getAttribute() );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleProgramStage( SetMap, IdentifiableObject> metadata, ProgramStage programStage )\n {\n if ( programStage == null ) return metadata;\n metadata.putValue( ProgramStage.class, programStage );\n programStage.getProgramStageDataElements().forEach( programStageDataElement -> handleProgramStageDataElement( metadata, programStageDataElement ) );\n programStage.getProgramStageSections().forEach( programStageSection -> handleProgramStageSection( metadata, programStageSection ) );\n handleDataEntryForm( metadata, programStage.getDataEntryForm() );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleProgramStageSection( SetMap, IdentifiableObject> metadata, ProgramStageSection programStageSection )\n {\n if ( programStageSection == null ) return metadata;\n metadata.putValue( ProgramStageSection.class, programStageSection );\n programStageSection.getProgramStageDataElements().forEach( programStageDataElement -> handleProgramStageDataElement( metadata, programStageDataElement ) );\n programStageSection.getProgramIndicators().forEach( programIndicator -> handleProgramIndicator( metadata, programIndicator ) );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleProgramIndicator( SetMap, IdentifiableObject> metadata, ProgramIndicator programIndicator )\n {\n if ( programIndicator == null ) return metadata;\n metadata.putValue( ProgramIndicator.class, programIndicator );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleProgramStageDataElement( SetMap, IdentifiableObject> metadata, ProgramStageDataElement programStageDataElement )\n {\n if ( programStageDataElement == null ) return metadata;\n metadata.putValue( ProgramStageDataElement.class, programStageDataElement );\n handleDataElement( metadata, programStageDataElement.getDataElement() );\n return metadata;\n }\n private SetMap, IdentifiableObject> handleTrackedEntity( SetMap, IdentifiableObject> metadata, TrackedEntity trackedEntity )\n {\n if ( trackedEntity == null ) return metadata;\n metadata.putValue( TrackedEntity.class, trackedEntity );\n return metadata;\n }\n}"}}},{"rowIdx":1272,"cells":{"answer":{"kind":"string","value":"package edu.wustl.catissuecore.action;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport org.apache.struts.action.ActionForm;\nimport org.apache.struts.action.ActionForward;\nimport org.apache.struts.action.ActionMapping;\nimport edu.wustl.catissuecore.actionForm.SimpleQueryInterfaceForm;\nimport edu.wustl.catissuecore.dao.DAOFactory;\nimport edu.wustl.catissuecore.dao.JDBCDAO;\nimport edu.wustl.catissuecore.util.global.Constants;\nimport edu.wustl.common.beans.NameValueBean;\nimport edu.wustl.common.util.dbManager.DAOException;\nimport edu.wustl.common.util.logger.Logger;\n/**\n * SimpleQueryInterfaceAction initializes the fields in the Simple Query Interface.\n * @author gautam_shetty\n */\npublic class SimpleQueryInterfaceAction extends SecureAction\n{\n /**\n * Overrides the execute method of Action class.\n */\n public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,\n HttpServletRequest request, HttpServletResponse response) throws Exception\n {\n SimpleQueryInterfaceForm simpleQueryInterfaceForm = (SimpleQueryInterfaceForm) form;\n int counter = Integer.parseInt(simpleQueryInterfaceForm.getCounter());\n for (int i=1;i<=counter;i++)\n {\n //Key of previous object.\n String prevKey = \"SimpleConditionsNode:\"+(i-1)+\"_Condition_DataElement_table\";\n String prevValue = (String)simpleQueryInterfaceForm.getValue(prevKey);\n //Key of present object.\n String key = \"SimpleConditionsNode:\"+i+\"_Condition_DataElement_table\";\n String value = (String)simpleQueryInterfaceForm.getValue(key);\n //Key of the next operator (AND/OR).\n String nextOperatorKey = \"SimpleConditionsNode:\"+i+\"_Operator_operator\";\n String nextOperatorValue = (String)simpleQueryInterfaceForm.getValue(nextOperatorKey);\n if (value != null)\n {\n if (!value.equals(Constants.SELECT_OPTION))\n {\n setColumnNames(request, i, value);\n }\n }\n String sql = \" select TABLE_A.ALIAS_NAME, TABLE_A.DISPLAY_NAME \" +\n \" from catissue_table_relation TABLE_R, \" +\n \" CATISSUE_QUERY_INTERFACE_TABLE_DATA TABLE_A, \" +\n \" CATISSUE_QUERY_INTERFACE_TABLE_DATA TABLE_B \" +\n \" where TABLE_R.PARENT_TABLE_ID = TABLE_A.TABLE_ID and \" +\n \" TABLE_R.CHILD_TABLE_ID = TABLE_B.TABLE_ID \";\n Logger.out.debug(\"Check sql.....................\"+sql);\n JDBCDAO jdbcDao = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO);\n jdbcDao.openSession(null);\n List checkList = jdbcDao.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null);\n jdbcDao.closeSession();\n if (i == counter)\n {\n if (prevValue != null)\n setNextTableNames(request, i, prevValue, checkList);\n else\n setAllTableNames(request);\n }\n else\n {\n if (nextOperatorValue != null && !\"\".equals(nextOperatorValue))\n {\n String prevValueDisplayName = null;\n String objectNameValueBeanList = \"objectList\"+i;\n JDBCDAO jdbcDAO = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO);\n jdbcDAO.openSession(null);\n sql = \"select DISPLAY_NAME from CATISSUE_QUERY_INTERFACE_TABLE_DATA where ALIAS_NAME='\"+value+\"'\";\n List list = jdbcDAO.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null);\n jdbcDAO.closeSession();\n if (!list.isEmpty())\n {\n List rowList = (List)list.get(0);\n prevValueDisplayName = (String)rowList.get(0);\n }\n NameValueBean nameValueBean = new NameValueBean();\n nameValueBean.setName(prevValueDisplayName);\n nameValueBean.setValue(value);\n List objectList = new ArrayList();\n objectList.add(nameValueBean);\n request.setAttribute(objectNameValueBeanList, objectList);\n }\n }\n }\n request.setAttribute(Constants.ATTRIBUTE_NAME_LIST, Constants.ATTRIBUTE_NAME_ARRAY);\n request.setAttribute(Constants.ATTRIBUTE_CONDITION_LIST, Constants.ATTRIBUTE_CONDITION_ARRAY);\n HttpSession session =request.getSession();\n session.setAttribute(Constants.SIMPLE_QUERY_ALIAS_NAME,null);\n session.setAttribute(Constants.SIMPLE_QUERY_COUNTER,null);\n session.setAttribute(Constants.SIMPLE_QUERY_MAP,null);\n String pageOf = request.getParameter(Constants.PAGEOF);\n request.setAttribute(Constants.PAGEOF, pageOf);\n String target = Constants.PAGEOF_EDIT_OBJECT;\n if (Constants.PAGEOF_SIMPLE_QUERY_INTERFACE.equals(pageOf))\n target = Constants.PAGEOF_SIMPLE_QUERY_INTERFACE;\n if(pageOf != null && pageOf.equals(\"pageOfSimpleQueryInterface\" ) )\n request.setAttribute(\"menuSelected\",new String(\"17\") );\n return mapping.findForward(target);\n }\n /**\n * Sets column names depending on the table name selected for that condition.\n * @param request HttpServletRequest\n * @param i number of row.\n * @param value table name.\n * @throws DAOException\n * @throws ClassNotFoundException\n */\n private void setColumnNames(HttpServletRequest request, int i, String value) throws DAOException, ClassNotFoundException\n {\n String attributeNameList = \"attributeNameList\"+i;\n String attributeDisplayNameList = \"attributeDisplayNameList\"+i;\n String sql = \" SELECT tableData2.ALIAS_NAME, temp.COLUMN_NAME, temp.ATTRIBUTE_TYPE, temp.TABLES_IN_PATH, temp.DISPLAY_NAME \" +\n \" from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData2 join \" +\n \" ( SELECT columnData.COLUMN_NAME, columnData.TABLE_ID, columnData.ATTRIBUTE_TYPE, \" +\n \" displayData.DISPLAY_NAME, relationData.TABLES_IN_PATH \" +\n \" FROM CATISSUE_QUERY_INTERFACE_COLUMN_DATA columnData, \" +\n \" CATISSUE_TABLE_RELATION relationData, \" +\n \" CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData, \" +\n \" CATISSUE_SEARCH_DISPLAY_DATA displayData \" +\n \" where relationData.CHILD_TABLE_ID = columnData.TABLE_ID and \" +\n \" relationData.PARENT_TABLE_ID = tableData.TABLE_ID and \" +\n \" relationData.RELATIONSHIP_ID = displayData.RELATIONSHIP_ID and \" +\n \" columnData.IDENTIFIER = displayData.COL_ID and \" +\n \" tableData.ALIAS_NAME = '\"+value+\"') as temp \" +\n \" on temp.TABLE_ID = tableData2.TABLE_ID \";\n Logger.out.debug(\"SQL*****************************\"+sql);\n JDBCDAO jdbcDao = new JDBCDAO();\n jdbcDao.openSession(null);\n List list = jdbcDao.executeQuery(sql, null, Constants.INSECURE_RETRIEVE, null,null);\n jdbcDao.closeSession();\n String [] columnNameList = new String[list.size()];\n String [] columnDisplayNameList = new String[list.size()];\n Iterator iterator = list.iterator();\n int j = 0, k=0;\n while (iterator.hasNext())\n {\n List rowList = (List)iterator.next();\n columnNameList[k] = (String)rowList.get(j++)+\".\"+(String)rowList.get(j++)\n +\".\"+(String)rowList.get(j++);\n String tablesInPath = (String)rowList.get(j++);\n if ((tablesInPath != null) && (\"\".equals(tablesInPath) == false))\n {\n columnNameList[k] = columnNameList[k]+\".\"+tablesInPath;\n }\n columnDisplayNameList[k] = (String)rowList.get(j++);\n j = 0;\n k++;\n }\n request.setAttribute(attributeNameList, columnNameList);\n request.setAttribute(attributeDisplayNameList, columnDisplayNameList);\n }\n /**\n * Sets the next table names depending on the table in the previous row.\n * @param request\n * @param i\n * @param prevValue previous table name.\n * @param nextOperatorValue\n * @param checkList\n * @throws DAOException\n * @throws ClassNotFoundException\n */\n private void setNextTableNames(HttpServletRequest request, int i, String prevValue, List checkList) throws DAOException, ClassNotFoundException\n {\n String objectNameList = \"objectList\"+i;\n List objectList = new ArrayList();\n String sql =\" (select temp.ALIAS_NAME, temp.DISPLAY_NAME \" +\n \" from \" +\n \" (select relationData.FIRST_TABLE_ID, tableData.ALIAS_NAME, tableData.DISPLAY_NAME \" +\n \" from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData join \" +\n \" CATISSUE_RELATED_TABLES_MAP relationData \" +\n \" on tableData.TABLE_ID = relationData.SECOND_TABLE_ID) as temp join CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData2 \" +\n \" on temp.FIRST_TABLE_ID = tableData2.TABLE_ID \" +\n \" where tableData2.ALIAS_NAME = '\"+prevValue+\"') \" +\n \" union \" +\n \" (select temp1.ALIAS_NAME, temp1.DISPLAY_NAME \" +\n \" from \" +\n \" (select relationData1.SECOND_TABLE_ID, tableData4.ALIAS_NAME, tableData4.DISPLAY_NAME \" +\n \" from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData4 join \" +\n \" CATISSUE_RELATED_TABLES_MAP relationData1 \" +\n \" on tableData4.TABLE_ID = relationData1.FIRST_TABLE_ID) as temp1 join CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData3 \" +\n \" on temp1.SECOND_TABLE_ID = tableData3.TABLE_ID \" +\n \" where tableData3.ALIAS_NAME = '\"+prevValue+\"')\";\n Logger.out.debug(\"TABLE SQL*****************************\"+sql);\n JDBCDAO jdbcDao = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO);\n jdbcDao.openSession(null);\n List list = jdbcDao.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null);\n jdbcDao.closeSession();\n //Adding NameValueBean of select option.\n NameValueBean nameValueBean = new NameValueBean();\n nameValueBean.setName(Constants.SELECT_OPTION);\n nameValueBean.setValue(\"-1\");\n objectList.add(nameValueBean);\n //Adding the NameValueBean of previous selected object.\n JDBCDAO jdbcDAO = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO);\n jdbcDAO.openSession(null);\n sql = \"select DISPLAY_NAME from CATISSUE_QUERY_INTERFACE_TABLE_DATA where ALIAS_NAME='\"+prevValue+\"'\";\n List prevValueDisplayNameList = jdbcDAO.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null);\n jdbcDAO.closeSession();\n if (!prevValueDisplayNameList.isEmpty())\n {\n List rowList = (List)prevValueDisplayNameList.get(0);\n nameValueBean = new NameValueBean();\n nameValueBean.setName((String)rowList.get(0));\n nameValueBean.setValue(prevValue);\n objectList.add(nameValueBean);\n }\n Iterator iterator = list.iterator();\n while (iterator.hasNext())\n {\n int j=0;\n List rowList = (List)iterator.next();\n if (checkForTable(rowList, checkList))\n {\n nameValueBean = new NameValueBean();\n nameValueBean.setValue((String)rowList.get(j++));\n nameValueBean.setName((String)rowList.get(j));\n objectList.add(nameValueBean);\n }\n }\n request.setAttribute(objectNameList, objectList);\n }\n /**\n * Returns the object id of the protection element that represents\n * the Action that is being requested for invocation.\n * @param clazz\n * @return\n */\n protected String getObjectIdForSecureMethodAccess(HttpServletRequest request)\n {\n String aliasName = request.getParameter(\"aliasName\");\n if(aliasName!=null && !aliasName.equals(\"\"))\n {\n return this.getClass().getName()+\"_\"+aliasName;\n }\n else\n {\n return super.getObjectIdForSecureMethodAccess(request);\n }\n }\n /**\n * @param mapping\n * @return\n */\n protected ActionForward getActionForward(HttpServletRequest request,ActionMapping mapping)\n {\n String aliasName = request.getParameter(\"aliasName\");\n if(aliasName.equals(\"User\") || aliasName.equals(\"Institution\") || aliasName.equals(\"Department\")|| aliasName.equals(\"CancerResearchGroup\")|| aliasName.equals(\"Site\")|| aliasName.equals(\"StorageType\")|| aliasName.equals(\"StorageContainer\")|| aliasName.equals(\"BioHazard\")|| aliasName.equals(\"CollectionProtocol\")|| aliasName.equals(\"DistributionProtocol\"))\n {\n return mapping.findForward(Constants.ACCESS_DENIED_ADMIN);\n }\n else if(aliasName.equals(\"Participant\") ||aliasName.equals(\"CollectionProtocolRegistration\") ||aliasName.equals(\"SpecimenCollectionGroup\") ||aliasName.equals(\"Specimen\") ||aliasName.equals(\"Distribution\"))\n {\n return mapping.findForward(Constants.ACCESS_DENIED_BIOSPECIMEN);\n }\n else\n {\n return mapping.findForward(Constants.ACCESS_DENIED);\n }\n }\n private boolean checkForTable(List rowList, List checkList)\n {\n String aliasName = (String)rowList.get(0), displayName = (String)rowList.get(1);\n Iterator iterator = checkList.iterator();\n while (iterator.hasNext())\n {\n List row = (List) iterator.next();\n if (aliasName.equals((String) row.get(0)) && displayName.equals((String) row.get(1)))\n {\n return true;\n }\n }\n return false;\n }\n /**\n * Sets all the tables in the simple query interface.\n * @param request\n * @throws DAOException\n * @throws ClassNotFoundException\n */\n private void setAllTableNames(HttpServletRequest request)throws DAOException, ClassNotFoundException\n {\n String sql = \" select distinct tableData.DISPLAY_NAME, tableData.ALIAS_NAME \" +\n \" from CATISSUE_TABLE_RELATION tableRelation join CATISSUE_QUERY_INTERFACE_TABLE_DATA \" +\n \" tableData on tableRelation.PARENT_TABLE_ID = tableData.TABLE_ID \";\n String aliasName = request.getParameter(Constants.TABLE_ALIAS_NAME);\n if ((aliasName != null) && (!\"\".equals(aliasName)))\n {\n sql = sql + \" where tableData.ALIAS_NAME = '\"+ aliasName +\"'\";\n request.setAttribute(Constants.TABLE_ALIAS_NAME,aliasName);\n }\n sql = sql + \" ORDER BY tableData.DISPLAY_NAME \";\n JDBCDAO jdbcDAO = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO);\n jdbcDAO.openSession(null);\n List tableList = jdbcDAO.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null);\n jdbcDAO.closeSession();\n String [] objectDisplayNames = null;\n String [] objectAliasNames = null;\n int i = 0;\n if ((aliasName != null) && (!\"\".equals(aliasName)))\n {\n objectDisplayNames = new String[tableList.size()];\n objectAliasNames = new String[tableList.size()];\n setColumnNames(request,1,aliasName);\n }\n else\n {\n objectDisplayNames = new String[tableList.size()+1];\n objectAliasNames = new String[tableList.size()+1];\n objectAliasNames[i] = \"-1\";\n objectDisplayNames[i] = Constants.SELECT_OPTION;\n i++;\n }\n Iterator objIterator = tableList.iterator();\n while (objIterator.hasNext())\n {\n List row = (List) objIterator.next();\n objectDisplayNames[i] = (String)row.get(0);\n objectAliasNames[i] = (String)row.get(1);\n i++;\n }\n request.setAttribute(Constants.OBJECT_DISPLAY_NAME_LIST, objectDisplayNames);\n request.setAttribute(Constants.OBJECT_ALIAS_NAME_LIST, objectAliasNames);\n }\n}"}}},{"rowIdx":1273,"cells":{"answer":{"kind":"string","value":"package org.jfree.text;\nimport java.awt.Font;\nimport java.awt.FontMetrics;\nimport java.awt.Graphics2D;\nimport java.awt.Paint;\nimport java.awt.Shape;\nimport java.awt.font.FontRenderContext;\nimport java.awt.font.LineMetrics;\nimport java.awt.font.TextLayout;\nimport java.awt.geom.AffineTransform;\nimport java.awt.geom.Rectangle2D;\nimport java.text.AttributedString;\nimport java.text.BreakIterator;\nimport org.jfree.base.BaseBoot;\nimport org.jfree.ui.TextAnchor;\nimport org.jfree.util.Log;\nimport org.jfree.util.LogContext;\nimport org.jfree.util.ObjectUtilities;\n/**\n * Some utility methods for working with text in Java2D.\n */\npublic class TextUtilities {\n /** Access to logging facilities. */\n protected static final LogContext logger = Log.createContext(\n TextUtilities.class);\n /**\n * A flag that controls whether or not the rotated string workaround is\n * used.\n */\n private static boolean useDrawRotatedStringWorkaround;\n /**\n * A flag that controls whether the FontMetrics.getStringBounds() method\n * is used or a workaround is applied.\n */\n private static boolean useFontMetricsGetStringBounds;\n static {\n try {\n boolean isJava14 = ObjectUtilities.isJDK14();\n String configRotatedStringWorkaround = BaseBoot.getInstance()\n .getGlobalConfig().getConfigProperty(\n \"org.jfree.text.UseDrawRotatedStringWorkaround\", \"auto\");\n if (configRotatedStringWorkaround.equals(\"auto\")) {\n useDrawRotatedStringWorkaround = !isJava14;\n }\n else {\n useDrawRotatedStringWorkaround\n = configRotatedStringWorkaround.equals(\"true\");\n }\n String configFontMetricsStringBounds = BaseBoot.getInstance()\n .getGlobalConfig().getConfigProperty(\n \"org.jfree.text.UseFontMetricsGetStringBounds\", \"auto\");\n if (configFontMetricsStringBounds.equals(\"auto\")) {\n useFontMetricsGetStringBounds = isJava14;\n } else {\n useFontMetricsGetStringBounds\n = configFontMetricsStringBounds.equals(\"true\");\n }\n }\n catch (Exception e) {\n // ignore everything.\n useDrawRotatedStringWorkaround = true;\n useFontMetricsGetStringBounds = true;\n }\n }\n /**\n * Private constructor prevents object creation.\n */\n private TextUtilities() {\n // prevent instantiation\n }\n /**\n * Creates a {@link TextBlock} from a String. Line breaks\n * are added where the String contains '\\n' characters.\n *\n * @param text the text.\n * @param font the font.\n * @param paint the paint.\n *\n * @return A text block.\n */\n public static TextBlock createTextBlock(String text, Font font,\n Paint paint) {\n if (text == null) {\n throw new IllegalArgumentException(\"Null 'text' argument.\");\n }\n TextBlock result = new TextBlock();\n String input = text;\n boolean moreInputToProcess = (text.length() > 0);\n int start = 0;\n while (moreInputToProcess) {\n int index = input.indexOf(\"\\n\");\n if (index > start) {\n String line = input.substring(start, index);\n if (index < input.length() - 1) {\n result.addLine(line, font, paint);\n input = input.substring(index + 1);\n }\n else {\n moreInputToProcess = false;\n }\n }\n else if (index == start) {\n if (index < input.length() - 1) {\n input = input.substring(index + 1);\n }\n else {\n moreInputToProcess = false;\n }\n }\n else {\n result.addLine(input, font, paint);\n moreInputToProcess = false;\n }\n }\n return result;\n }\n /**\n * Creates a new text block from the given string, breaking the\n * text into lines so that the maxWidth value is\n * respected.\n *\n * @param text the text.\n * @param font the font.\n * @param paint the paint.\n * @param maxWidth the maximum width for each line.\n * @param measurer the text measurer.\n *\n * @return A text block.\n */\n public static TextBlock createTextBlock(String text, Font font,\n Paint paint, float maxWidth, TextMeasurer measurer) {\n return createTextBlock(text, font, paint, maxWidth, Integer.MAX_VALUE,\n measurer);\n }\n /**\n * Creates a new text block from the given string, breaking the\n * text into lines so that the maxWidth value is\n * respected.\n *\n * @param text the text.\n * @param font the font.\n * @param paint the paint.\n * @param maxWidth the maximum width for each line.\n * @param maxLines the maximum number of lines.\n * @param measurer the text measurer.\n *\n * @return A text block.\n */\n public static TextBlock createTextBlock(String text, Font font,\n Paint paint, float maxWidth, int maxLines, TextMeasurer measurer) {\n TextBlock result = new TextBlock();\n BreakIterator iterator = BreakIterator.getLineInstance();\n iterator.setText(text);\n int current = 0;\n int lines = 0;\n int length = text.length();\n while (current < length && lines < maxLines) {\n int next = nextLineBreak(text, current, maxWidth, iterator,\n measurer);\n if (next == BreakIterator.DONE) {\n result.addLine(text.substring(current), font, paint);\n return result;\n }\n result.addLine(text.substring(current, next), font, paint);\n lines++;\n current = next;\n while (current < text.length()&& text.charAt(current) == '\\n') {\n current++;\n }\n }\n if (current < length) {\n TextLine lastLine = result.getLastLine();\n TextFragment lastFragment = lastLine.getLastTextFragment();\n String oldStr = lastFragment.getText();\n String newStr = \"...\";\n if (oldStr.length() > 3) {\n newStr = oldStr.substring(0, oldStr.length() - 3) + \"...\";\n }\n lastLine.removeFragment(lastFragment);\n TextFragment newFragment = new TextFragment(newStr,\n lastFragment.getFont(), lastFragment.getPaint());\n lastLine.addFragment(newFragment);\n }\n return result;\n }\n /**\n * Returns the character index of the next line break.\n *\n * @param text the text (null not permitted).\n * @param start the start index.\n * @param width the target display width.\n * @param iterator the word break iterator.\n * @param measurer the text measurer.\n *\n * @return The index of the next line break.\n */\n private static int nextLineBreak(String text, int start, float width,\n BreakIterator iterator, TextMeasurer measurer) {\n // this method is (loosely) based on code in JFreeReport's\n // TextParagraph class\n int current = start;\n int end;\n float x = 0.0f;\n boolean firstWord = true;\n int newline = text.indexOf('\\n', start);\n if (newline < 0) {\n newline = Integer.MAX_VALUE;\n }\n while (((end = iterator.following(current)) != BreakIterator.DONE)) {\n x += measurer.getStringWidth(text, current, end);\n if (x > width) {\n if (firstWord) {\n while (measurer.getStringWidth(text, start, end) > width) {\n end\n if (end <= start) {\n return end;\n }\n }\n return end;\n }\n else {\n end = iterator.previous();\n return end;\n }\n }\n else {\n if (end > newline) {\n return newline;\n }\n }\n // we found at least one word that fits ...\n firstWord = false;\n current = end;\n }\n return BreakIterator.DONE;\n }\n /**\n * Returns the bounds for the specified text.\n *\n * @param text the text (null permitted).\n * @param g2 the graphics context (not null).\n * @param fm the font metrics (not null).\n *\n * @return The text bounds (null if the text\n * argument is null).\n */\n public static Rectangle2D getTextBounds(String text, Graphics2D g2,\n FontMetrics fm) {\n Rectangle2D bounds;\n if (TextUtilities.useFontMetricsGetStringBounds) {\n bounds = fm.getStringBounds(text, g2);\n // getStringBounds() can return incorrect height for some Unicode\n // characters...see bug parade 6183356, let's replace it with\n // something correct\n LineMetrics lm = fm.getFont().getLineMetrics(text,\n g2.getFontRenderContext());\n bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(),\n lm.getHeight());\n }\n else {\n double width = fm.stringWidth(text);\n double height = fm.getHeight();\n if (logger.isDebugEnabled()) {\n logger.debug(\"Height = \" + height);\n }\n bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width,\n height);\n }\n return bounds;\n }\n /**\n * Draws a string such that the specified anchor point is aligned to the\n * given (x, y) location.\n *\n * @param text the text.\n * @param g2 the graphics device.\n * @param x the x coordinate (Java 2D).\n * @param y the y coordinate (Java 2D).\n * @param anchor the anchor location.\n *\n * @return The text bounds (adjusted for the text position).\n */\n public static Rectangle2D drawAlignedString(String text, Graphics2D g2,\n float x, float y, TextAnchor anchor) {\n Rectangle2D textBounds = new Rectangle2D.Double();\n float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor,\n textBounds);\n // adjust text bounds to match string position\n textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2],\n textBounds.getWidth(), textBounds.getHeight());\n g2.drawString(text, x + adjust[0], y + adjust[1]);\n return textBounds;\n }\n /**\n * A utility method that calculates the anchor offsets for a string.\n * Normally, the (x, y) coordinate for drawing text is a point on the\n * baseline at the left of the text string. If you add these offsets to\n * (x, y) and draw the string, then the anchor point should coincide with\n * the (x, y) point.\n *\n * @param g2 the graphics device (not null).\n * @param text the text.\n * @param anchor the anchor point.\n * @param textBounds the text bounds (if not null, this\n * object will be updated by this method to match the\n * string bounds).\n *\n * @return The offsets.\n */\n private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,\n String text, TextAnchor anchor, Rectangle2D textBounds) {\n float[] result = new float[3];\n FontRenderContext frc = g2.getFontRenderContext();\n Font f = g2.getFont();\n FontMetrics fm = g2.getFontMetrics(f);\n Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);\n LineMetrics metrics = f.getLineMetrics(text, frc);\n float ascent = metrics.getAscent();\n result[2] = -ascent;\n float halfAscent = ascent / 2.0f;\n float descent = metrics.getDescent();\n float leading = metrics.getLeading();\n float xAdj = 0.0f;\n float yAdj = 0.0f;\n if (anchor.isHorizontalCenter()) {\n xAdj = (float) -bounds.getWidth() / 2.0f;\n }\n else if (anchor.isRight()) {\n xAdj = (float) -bounds.getWidth();\n }\n if (anchor.isTop()) {\n yAdj = -descent - leading + (float) bounds.getHeight();\n }\n else if (anchor.isHalfAscent()) {\n yAdj = halfAscent;\n }\n else if (anchor.isVerticalCenter()) {\n yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);\n }\n else if (anchor.isBaseline()) {\n yAdj = 0.0f;\n }\n else if (anchor.isBottom()) {\n yAdj = -metrics.getDescent() - metrics.getLeading();\n }\n if (textBounds != null) {\n textBounds.setRect(bounds);\n }\n result[0] = xAdj;\n result[1] = yAdj;\n return result;\n }\n /**\n * A utility method for drawing rotated text.\n *

    \n * A common rotation is -Math.PI/2 which draws text 'vertically' (with the\n * top of the characters on the left).\n *\n * @param text the text.\n * @param g2 the graphics device.\n * @param angle the angle of the (clockwise) rotation (in radians).\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public static void drawRotatedString(String text, Graphics2D g2,\n double angle, float x, float y) {\n drawRotatedString(text, g2, x, y, angle, x, y);\n }\n /**\n * A utility method for drawing rotated text.\n *

    \n * A common rotation is -Math.PI/2 which draws text 'vertically' (with the\n * top of the characters on the left).\n *\n * @param text the text.\n * @param g2 the graphics device.\n * @param textX the x-coordinate for the text (before rotation).\n * @param textY the y-coordinate for the text (before rotation).\n * @param angle the angle of the (clockwise) rotation (in radians).\n * @param rotateX the point about which the text is rotated.\n * @param rotateY the point about which the text is rotated.\n */\n public static void drawRotatedString(String text, Graphics2D g2,\n float textX, float textY,\n double angle, float rotateX, float rotateY) {\n if ((text == null) || (text.equals(\"\"))) {\n return;\n }\n if (angle == 0.0) {\n drawAlignedString(text, g2, textY, textY, TextAnchor.BASELINE_LEFT);\n return;\n }\n AffineTransform saved = g2.getTransform();\n AffineTransform rotate = AffineTransform.getRotateInstance(\n angle, rotateX, rotateY);\n g2.transform(rotate);\n if (useDrawRotatedStringWorkaround) {\n // workaround for JDC bug ID 4312117 and others...\n TextLayout tl = new TextLayout(text, g2.getFont(),\n g2.getFontRenderContext());\n tl.draw(g2, textX, textY);\n }\n else {\n AttributedString as = new AttributedString(text,\n g2.getFont().getAttributes());\n g2.drawString(as.getIterator(), textX, textY);\n }\n g2.setTransform(saved);\n }\n /**\n * Draws a string that is aligned by one anchor point and rotated about\n * another anchor point.\n *\n * @param text the text.\n * @param g2 the graphics device.\n * @param x the x-coordinate for positioning the text.\n * @param y the y-coordinate for positioning the text.\n * @param textAnchor the text anchor.\n * @param angle the rotation angle.\n * @param rotationX the x-coordinate for the rotation anchor point.\n * @param rotationY the y-coordinate for the rotation anchor point.\n */\n public static void drawRotatedString(String text, Graphics2D g2,\n float x, float y, TextAnchor textAnchor,\n double angle, float rotationX, float rotationY) {\n if (text == null || text.equals(\"\")) {\n return;\n }\n if (angle == 0.0) {\n drawAlignedString(text, g2, x, y, textAnchor);\n } else {\n float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text,\n textAnchor);\n drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle,\n rotationX, rotationY);\n }\n }\n /**\n * Draws a string that is aligned by one anchor point and rotated about\n * another anchor point.\n *\n * @param text the text.\n * @param g2 the graphics device.\n * @param x the x-coordinate for positioning the text.\n * @param y the y-coordinate for positioning the text.\n * @param textAnchor the text anchor.\n * @param angle the rotation angle (in radians).\n * @param rotationAnchor the rotation anchor.\n */\n public static void drawRotatedString(String text, Graphics2D g2,\n float x, float y, TextAnchor textAnchor,\n double angle, TextAnchor rotationAnchor) {\n if (text == null || text.equals(\"\")) {\n return;\n }\n if (angle == 0.0) {\n drawAlignedString(text, g2, x, y, textAnchor);\n } else {\n float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text,\n textAnchor);\n float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,\n rotationAnchor);\n drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1],\n angle, x + textAdj[0] + rotateAdj[0],\n y + textAdj[1] + rotateAdj[1]);\n }\n }\n /**\n * Returns a shape that represents the bounds of the string after the\n * specified rotation has been applied.\n *\n * @param text the text (null permitted).\n * @param g2 the graphics device.\n * @param x the x coordinate for the anchor point.\n * @param y the y coordinate for the anchor point.\n * @param textAnchor the text anchor.\n * @param angle the angle.\n * @param rotationAnchor the rotation anchor.\n *\n * @return The bounds (possibly null).\n */\n public static Shape calculateRotatedStringBounds(String text, Graphics2D g2,\n float x, float y, TextAnchor textAnchor,\n double angle, TextAnchor rotationAnchor) {\n if (text == null || text.equals(\"\")) {\n return null;\n }\n float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor);\n if (logger.isDebugEnabled()) {\n logger.debug(\"TextBoundsAnchorOffsets = \" + textAdj[0] + \", \"\n + textAdj[1]);\n }\n float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,\n rotationAnchor);\n if (logger.isDebugEnabled()) {\n logger.debug(\"RotationAnchorOffsets = \" + rotateAdj[0] + \", \"\n + rotateAdj[1]);\n }\n Shape result = calculateRotatedStringBounds(text, g2,\n x + textAdj[0], y + textAdj[1], angle,\n x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]);\n return result;\n }\n /**\n * A utility method that calculates the anchor offsets for a string.\n * Normally, the (x, y) coordinate for drawing text is a point on the\n * baseline at the left of the text string. If you add these offsets to\n * (x, y) and draw the string, then the anchor point should coincide with\n * the (x, y) point.\n *\n * @param g2 the graphics device (not null).\n * @param text the text.\n * @param anchor the anchor point.\n *\n * @return The offsets.\n */\n private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,\n String text, TextAnchor anchor) {\n float[] result = new float[2];\n FontRenderContext frc = g2.getFontRenderContext();\n Font f = g2.getFont();\n FontMetrics fm = g2.getFontMetrics(f);\n Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);\n LineMetrics metrics = f.getLineMetrics(text, frc);\n float ascent = metrics.getAscent();\n float halfAscent = ascent / 2.0f;\n float descent = metrics.getDescent();\n float leading = metrics.getLeading();\n float xAdj = 0.0f;\n float yAdj = 0.0f;\n if (anchor.isHorizontalCenter()) {\n xAdj = (float) -bounds.getWidth() / 2.0f;\n }\n else if (anchor.isRight()) {\n xAdj = (float) -bounds.getWidth();\n }\n if (anchor.isTop()) {\n yAdj = -descent - leading + (float) bounds.getHeight();\n }\n else if (anchor.isHalfAscent()) {\n yAdj = halfAscent;\n }\n else if (anchor.isVerticalCenter()) {\n yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);\n }\n else if (anchor.isBaseline()) {\n yAdj = 0.0f;\n }\n else if (anchor.isBottom()) {\n yAdj = -metrics.getDescent() - metrics.getLeading();\n }\n result[0] = xAdj;\n result[1] = yAdj;\n return result;\n }\n /**\n * A utility method that calculates the rotation anchor offsets for a\n * string. These offsets are relative to the text starting coordinate\n * (BASELINE_LEFT).\n *\n * @param g2 the graphics device.\n * @param text the text.\n * @param anchor the anchor point.\n *\n * @return The offsets.\n */\n private static float[] deriveRotationAnchorOffsets(Graphics2D g2,\n String text, TextAnchor anchor) {\n float[] result = new float[2];\n FontRenderContext frc = g2.getFontRenderContext();\n LineMetrics metrics = g2.getFont().getLineMetrics(text, frc);\n FontMetrics fm = g2.getFontMetrics();\n Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);\n float ascent = metrics.getAscent();\n float halfAscent = ascent / 2.0f;\n float descent = metrics.getDescent();\n float leading = metrics.getLeading();\n float xAdj = 0.0f;\n float yAdj = 0.0f;\n if (anchor.isLeft()) {\n xAdj = 0.0f;\n }\n else if (anchor.isHorizontalCenter()) {\n xAdj = (float) bounds.getWidth() / 2.0f;\n }\n else if (anchor.isRight()) {\n xAdj = (float) bounds.getWidth();\n }\n if (anchor.isTop()) {\n yAdj = descent + leading - (float) bounds.getHeight();\n }\n else if (anchor.isVerticalCenter()) {\n yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);\n }\n else if (anchor.isHalfAscent()) {\n yAdj = -halfAscent;\n }\n else if (anchor.isBaseline()) {\n yAdj = 0.0f;\n }\n else if (anchor.isBottom()) {\n yAdj = metrics.getDescent() + metrics.getLeading();\n }\n result[0] = xAdj;\n result[1] = yAdj;\n return result;\n }\n /**\n * Returns a shape that represents the bounds of the string after the\n * specified rotation has been applied.\n *\n * @param text the text (null permitted).\n * @param g2 the graphics device.\n * @param textX the x coordinate for the text.\n * @param textY the y coordinate for the text.\n * @param angle the angle.\n * @param rotateX the x coordinate for the rotation point.\n * @param rotateY the y coordinate for the rotation point.\n *\n * @return The bounds (null if text is\n * null or has zero length).\n */\n public static Shape calculateRotatedStringBounds(String text, Graphics2D g2,\n float textX, float textY, double angle, float rotateX,\n float rotateY) {\n if ((text == null) || (text.equals(\"\"))) {\n return null;\n }\n FontMetrics fm = g2.getFontMetrics();\n Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);\n AffineTransform translate = AffineTransform.getTranslateInstance(\n textX, textY);\n Shape translatedBounds = translate.createTransformedShape(bounds);\n AffineTransform rotate = AffineTransform.getRotateInstance(\n angle, rotateX, rotateY);\n Shape result = rotate.createTransformedShape(translatedBounds);\n return result;\n }\n /**\n * Returns the flag that controls whether the FontMetrics.getStringBounds()\n * method is used or not. If you are having trouble with label alignment\n * or positioning, try changing the value of this flag.\n *\n * @return A boolean.\n */\n public static boolean getUseFontMetricsGetStringBounds() {\n return useFontMetricsGetStringBounds;\n }\n /**\n * Sets the flag that controls whether the FontMetrics.getStringBounds()\n * method is used or not. If you are having trouble with label alignment\n * or positioning, try changing the value of this flag.\n *\n * @param use the flag.\n */\n public static void setUseFontMetricsGetStringBounds(boolean use) {\n useFontMetricsGetStringBounds = use;\n }\n /**\n * Returns the flag that controls whether or not a workaround is used for\n * drawing rotated strings.\n *\n * @return A boolean.\n */\n public static boolean isUseDrawRotatedStringWorkaround() {\n return useDrawRotatedStringWorkaround;\n }\n /**\n * Sets the flag that controls whether or not a workaround is used for\n * drawing rotated strings. The related bug is on Sun's bug parade\n * (id 4312117) and the workaround involves using a TextLayout\n * instance to draw the text instead of calling the\n * drawString() method in the Graphics2D class.\n *\n * @param use the new flag value.\n */\n public static void setUseDrawRotatedStringWorkaround(final boolean use) {\n useDrawRotatedStringWorkaround = use;\n }\n}"}}},{"rowIdx":1274,"cells":{"answer":{"kind":"string","value":"package org.eclipse.birt.report.engine.presentation;\nimport java.io.BufferedInputStream;\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.ref.SoftReference;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport org.eclipse.birt.core.exception.BirtException;\nimport org.eclipse.birt.core.format.DateFormatter;\nimport org.eclipse.birt.core.format.NumberFormatter;\nimport org.eclipse.birt.core.format.StringFormatter;\nimport org.eclipse.birt.core.template.TextTemplate;\nimport org.eclipse.birt.data.engine.api.IBaseQueryDefinition;\nimport org.eclipse.birt.report.engine.api.CachedImage;\nimport org.eclipse.birt.report.engine.api.EngineConstants;\nimport org.eclipse.birt.report.engine.api.IHTMLImageHandler;\nimport org.eclipse.birt.report.engine.api.IImage;\nimport org.eclipse.birt.report.engine.api.IRenderOption;\nimport org.eclipse.birt.report.engine.content.ContentVisitorAdapter;\nimport org.eclipse.birt.report.engine.content.ICellContent;\nimport org.eclipse.birt.report.engine.content.IContent;\nimport org.eclipse.birt.report.engine.content.IDataContent;\nimport org.eclipse.birt.report.engine.content.IForeignContent;\nimport org.eclipse.birt.report.engine.content.IImageContent;\nimport org.eclipse.birt.report.engine.content.ILabelContent;\nimport org.eclipse.birt.report.engine.content.IListContent;\nimport org.eclipse.birt.report.engine.content.IPageContent;\nimport org.eclipse.birt.report.engine.content.IReportContent;\nimport org.eclipse.birt.report.engine.content.IRowContent;\nimport org.eclipse.birt.report.engine.content.IStyle;\nimport org.eclipse.birt.report.engine.content.ITableContent;\nimport org.eclipse.birt.report.engine.content.ITextContent;\nimport org.eclipse.birt.report.engine.css.engine.value.css.CSSValueConstants;\nimport org.eclipse.birt.report.engine.executor.ExecutionContext;\nimport org.eclipse.birt.report.engine.executor.template.TemplateExecutor;\nimport org.eclipse.birt.report.engine.extension.IBaseResultSet;\nimport org.eclipse.birt.report.engine.extension.IQueryResultSet;\nimport org.eclipse.birt.report.engine.extension.IReportItemPresentation;\nimport org.eclipse.birt.report.engine.extension.IRowSet;\nimport org.eclipse.birt.report.engine.extension.internal.ExtensionManager;\nimport org.eclipse.birt.report.engine.extension.internal.RowSet;\nimport org.eclipse.birt.report.engine.extension.internal.SingleRowSet;\nimport org.eclipse.birt.report.engine.ir.ExtendedItemDesign;\nimport org.eclipse.birt.report.engine.ir.ListItemDesign;\nimport org.eclipse.birt.report.engine.ir.ReportItemDesign;\nimport org.eclipse.birt.report.engine.ir.TextItemDesign;\nimport org.eclipse.birt.report.engine.script.internal.OnRenderScriptVisitor;\nimport org.eclipse.birt.report.model.api.DesignElementHandle;\nimport org.eclipse.birt.report.model.api.ExtendedItemHandle;\nimport org.eclipse.birt.report.model.api.ModuleUtil;\nimport org.eclipse.birt.report.model.api.ReportDesignHandle;\nimport org.eclipse.birt.report.model.api.ReportElementHandle;\nimport org.w3c.dom.css.CSSValue;\nimport com.ibm.icu.util.ULocale;\npublic class LocalizedContentVisitor extends ContentVisitorAdapter\n{\n protected static Logger logger = Logger\n .getLogger( LocalizedContentVisitor.class.getName( ) );\n private ExecutionContext context;\n private Locale locale;\n private String outputFormat;\n protected HashMap templates = new HashMap( );\n private OnRenderScriptVisitor onRenderVisitor;\n public LocalizedContentVisitor( ExecutionContext context )\n {\n this.context = context;\n this.locale = context.getLocale( );\n this.outputFormat = context.getOutputFormat( );\n this.onRenderVisitor = new OnRenderScriptVisitor( context );\n }\n IReportContent getReportContent( )\n {\n return context.getReportContent( );\n }\n ReportDesignHandle getReportDesign( )\n {\n return context.getDesign( );\n }\n public IContent localize(IContent content)\n {\n Object value = content.accept( this, content );\n return (IContent) value;\n }\n protected IContent localizeAllChildren( IContent content )\n {\n ArrayList children = (ArrayList) content.getChildren( );\n if ( children != null )\n {\n for ( int i = 0; i < children.size( ); i++ )\n {\n IContent child = (IContent) children.get( i );\n IContent localChild = localize( child );\n if ( localChild != child )\n {\n // replace the child with the licallized child.\n children.set( i, localChild );\n // set the locallized child's parent as orient child's\n // parent.\n localChild.setParent( content );\n // copy all children of this child to its localized child,\n // also change all children's parent to this localized\n // child.\n Collection childrenOfLocalChild = localChild.getChildren( );\n Iterator iter = child.getChildren( ).iterator( );\n while ( iter.hasNext( ) )\n {\n IContent childOfChild = (IContent) iter.next( );\n if ( !childrenOfLocalChild.contains( childOfChild ) )\n {\n childOfChild.setParent( localChild );\n childrenOfLocalChild.add( childOfChild );\n }\n }\n }\n localizeAllChildren( localChild );\n }\n }\n return content;\n }\n public Object visitPage( IPageContent page, Object value )\n {\n return page;\n }\n protected TextTemplate parseTemplate( String text )\n {\n SoftReference templateRef = (SoftReference) templates.get( text );\n TextTemplate template = null;\n if ( templateRef != null )\n {\n template = (TextTemplate) templateRef.get( );\n if ( template != null )\n {\n return template;\n }\n }\n try\n {\n template = new org.eclipse.birt.core.template.TemplateParser( )\n .parse( text );\n templateRef = new SoftReference( template );\n templates.put( text, templateRef );\n }\n catch ( Exception ex )\n {\n ex.printStackTrace( );\n }\n return template;\n }\n String executeTemplate( TextTemplate template, HashMap values )\n {\n return new TemplateExecutor( context ).execute( template, values );\n }\n public Object visitList( IListContent list, Object value)\n {\n if ( list.getGenerateBy( ) instanceof ListItemDesign )\n {\n handleOnRender( list );\n }\n return list;\n }\n public Object visitTable( ITableContent table, Object value )\n {\n handleOnRender( table );\n String captionText = table.getCaption( );\n String captionKey = table.getCaptionKey( );\n captionText = localize( table, captionKey, captionText );\n table.setCaption( captionText );\n return table;\n }\n public Object visitRow( IRowContent row, Object value )\n {\n handleOnRender( row );\n return row;\n }\n public Object visitCell( ICellContent cell, Object value )\n {\n handleOnRender( cell );\n return cell;\n }\n /**\n * handle the data content.\n *\n * @param data\n * data content object\n */\n public Object visitData( IDataContent data, Object value )\n {\n handleOnRender( data );\n processData( data );\n return data;\n }\n /**\n * process the data content\n *\n *

  • localize the help text\n *
  • format the value\n *
  • handle it as it is an text.\n *\n * @param data\n * data object\n */\n protected void processData( IDataContent data )\n {\n String helpText = localize( data, data.getHelpKey( ), data.getHelpText( ) );\n data.setHelpText( helpText );\n String text = \"\"; //$NON-NLS-1$\n if ( data.getLabelKey( ) != null || data.getLabelText( ) != null )\n {\n text = localize( data, data.getLabelKey( ), data.getLabelText( ) );\n }\n else\n {\n Object value = data.getValue( );\n if ( value != null )\n {\n IStyle style = data.getComputedStyle( );\n if ( value instanceof Number )\n {\n String format = style.getNumberFormat( );\n NumberFormatter fmt = context.getNumberFormatter( format );\n text = fmt.format( (Number) value );\n CSSValue align = style\n .getProperty( IStyle.STYLE_NUMBER_ALIGN );\n if ( align != null && align != CSSValueConstants.NONE_VALUE )\n {\n data.getStyle( ).setProperty( IStyle.STYLE_TEXT_ALIGN,\n align );\n }\n }\n else if ( value instanceof String )\n {\n StringFormatter fmt = context.getStringFormatter( style\n .getStringFormat( ) );\n text = fmt.format( (String) value );\n }\n else if ( value instanceof Date )\n {\n DateFormatter fmt = context.getDateFormatter( style\n .getDateFormat( ) );\n text = fmt.format( (Date) value );\n }\n else\n {\n text = value.toString( );\n }\n }\n }\n //text can be null value after applying format\n if(text!=null)\n {\n data.setText( text );\n }\n else\n {\n data.setText( \"\" ); //$NON-NLS-1$\n }\n }\n /**\n * handle the label.\n *\n * @param label\n * label content\n */\n public Object visitLabel( ILabelContent label, Object value )\n {\n handleOnRender( label );\n processLabel( label );\n return label;\n }\n /**\n * process the label content\n *\n *
  • localize the help text\n *
  • localize the label content\n *
  • handle it as it is an text\n *\n * @param label\n * label object\n */\n protected void processLabel( ILabelContent label )\n {\n String helpText = localize( label, label.getHelpKey( ), label.getHelpText( ) );\n label.setHelpText( helpText );\n if ( label.getText( ) == null )\n {\n String text = localize( label, label.getLabelKey( ), label.getLabelText( ) );\n label.setText( text );\n }\n }\n public Object visitText( ITextContent text, Object value )\n {\n handleOnRender( text );\n return value;\n }\n public Object visitForeign( IForeignContent foreignContent, Object value )\n {\n IReportContent reportContent = getReportContent( );\n String rawFormat = foreignContent.getRawType( );\n Object rawValue = foreignContent.getRawValue( );\n if ( IForeignContent.TEMPLATE_TYPE.equals( rawFormat ) )\n {\n handleOnRender( foreignContent );\n processTemplateContent( foreignContent );\n return foreignContent;\n }\n if ( IForeignContent.EXTERNAL_TYPE.equals( rawFormat ) )\n {\n return processExtendedContent( foreignContent );\n }\n if ( IForeignContent.IMAGE_TYPE.equals( rawFormat ) )\n {\n if ( rawValue instanceof IImageContent )\n {\n IImageContent image = (IImageContent) rawValue;\n processImage( image );\n return image;\n }\n if ( rawValue instanceof byte[] )\n {\n IImageContent imageContent = reportContent\n .createImageContent( foreignContent );\n imageContent.setImageSource( IImageContent.IMAGE_EXPRESSION );\n imageContent.setData( (byte[]) rawValue );\n processImage( imageContent );\n return imageContent;\n }\n }\n if ( IForeignContent.TEXT_TYPE.equals( rawFormat ) )\n {\n handleOnRender( foreignContent );\n ITextContent textContent = reportContent\n .createDataContent( foreignContent );\n textContent.setText( rawValue == null ? \"\" : rawValue.toString( ) ); //$NON-NLS-1$\n return textContent;\n }\n if ( IForeignContent.HTML_TYPE.equals( rawFormat ) )\n {\n handleOnRender( foreignContent );\n String key = foreignContent.getRawKey( );\n if (key != null)\n {\n String text = localize( foreignContent, key, null);\n if (text != null)\n {\n foreignContent.setRawValue( text );\n }\n }\n return foreignContent;\n }\n if ( IForeignContent.VALUE_TYPE.equals( rawFormat ) )\n {\n handleOnRender( foreignContent );\n IDataContent dataContent = reportContent\n .createDataContent( foreignContent );\n dataContent.setValue( rawValue );\n processData( dataContent );\n return dataContent;\n }\n return foreignContent;\n }\n /**\n * localzie the text.\n *\n * @param key\n * text key\n * @param text\n * default text\n * @return localized text.\n */\n private String localize( IContent content, String key, String text )\n {\n assert ( content != null );\n if ( content.getGenerateBy( ) != null )\n {\n DesignElementHandle element = ( (ReportItemDesign) content\n .getGenerateBy( ) ).getHandle( );\n if ( key != null && element != null )\n {\n String t = ModuleUtil.getExternalizedValue( element, key, text,\n ULocale.forLocale( locale ) );\n if ( t != null )\n {\n return t;\n }\n }\n }\n return text;\n }\n public Object visitImage( IImageContent image, Object value )\n {\n handleOnRender( image );\n processImage( image );\n return image;\n }\n protected void processImage( IImageContent image )\n {\n String altText = localize( image, image.getAltTextKey( ), image.getAltText( ) );\n image.setAltText( altText );\n String helpText = localize( image, image.getHelpKey( ), image.getHelpText( ) );\n image.setHelpText( helpText );\n }\n /**\n * handle the template result.\n *\n * @param foreignContent\n */\n protected void processTemplateContent( IForeignContent foreignContent )\n {\n assert IForeignContent.TEMPLATE_TYPE.equals( foreignContent\n .getRawType( ) );\n if ( foreignContent.getGenerateBy( ) instanceof TextItemDesign )\n {\n TextItemDesign design = (TextItemDesign) foreignContent\n .getGenerateBy( );\n String text = null;\n HashMap rawValues = null;\n if ( foreignContent.getRawValue( ) instanceof Object[] )\n {\n Object[] rawValue = (Object[]) foreignContent.getRawValue( );\n assert rawValue.length == 2;\n assert rawValue[0] == null || rawValue[0] instanceof String;\n if ( rawValue[0] != null )\n {\n text = (String )rawValue[0];\n }\n if ( rawValue[1] instanceof HashMap )\n {\n rawValues = (HashMap)rawValue[1];\n }\n }\n if ( text == null )\n {\n text = localize( foreignContent, design.getTextKey( ), design.getText( ) );\n }\n TextTemplate template = parseTemplate( text );\n String result = executeTemplate( template, rawValues );\n foreignContent.setRawType( IForeignContent.HTML_TYPE );\n foreignContent.setRawValue( result );\n }\n }\n protected String getOutputFormat()\n {\n return outputFormat;\n }\n /**\n * @return whether the output format is for printing\n */\n protected boolean isForPrinting( )\n {\n String outputFormat = getOutputFormat( );\n if ( \"FO\".equalsIgnoreCase( outputFormat )\n || \"PDF\".equalsIgnoreCase( outputFormat )\n ||\"POSTSCRIPT\".equalsIgnoreCase( outputFormat ))\n return true;\n return false;\n }\n /**\n * handle an extended item.\n *\n * @param content\n * the object.\n */\n protected IContent processExtendedContent( IForeignContent content )\n {\n assert IForeignContent.EXTERNAL_TYPE.equals( content.getRawType( ) );\n assert content.getGenerateBy( ) instanceof ExtendedItemDesign;\n IContent generatedContent = content;\n ExtendedItemDesign design = (ExtendedItemDesign) content\n .getGenerateBy( );\n ExtendedItemHandle handle = (ExtendedItemHandle) design.getHandle( );\n String tagName = handle.getExtensionName( );\n if ( \"Chart\".equals( tagName ) )\n {\n IHTMLImageHandler imageHandler = context.getImageHandler( );\n if ( imageHandler != null )\n {\n String imageId = content.getInstanceID( ).toString( );\n CachedImage cachedImage = imageHandler.getCachedImage( imageId,\n IImage.CUSTOM_IMAGE, context.getReportContext( ) );\n if ( cachedImage != null )\n {\n IImageContent imageObj = getReportContent( )\n .createImageContent( content );\n imageObj.setParent( content.getParent( ) );\n // Set image map\n imageObj.setImageSource( IImageContent.IMAGE_FILE );\n imageObj.setURI( cachedImage.getURL( ) );\n imageObj.setMIMEType( cachedImage.getMIMEType( ) );\n imageObj.setImageMap( cachedImage.getImageMap( ) );\n imageObj.setAltText( content.getAltText( ) );\n imageObj.setAltTextKey( content.getAltTextKey( ) );\n processImage( imageObj );\n return imageObj;\n }\n }\n }\n // call the presentation peer to create the content object\n IReportItemPresentation itemPresentation = ExtensionManager\n .getInstance( ).createPresentationItem( tagName );\n if ( itemPresentation != null )\n {\n itemPresentation.setModelObject( handle );\n itemPresentation.setApplicationClassLoader( context\n .getApplicationClassLoader( ) );\n itemPresentation.setScriptContext( context.getReportContext( ) );\n IBaseQueryDefinition[] queries = (IBaseQueryDefinition[])design.getQueries( );\n itemPresentation.setReportQueries( queries );\n itemPresentation.setDynamicStyle( content.getComputedStyle( ) );\n Map appContext = context.getAppContext( );\n int resolution = 0;\n if ( appContext != null )\n {\n Object tmp = appContext.get( EngineConstants.APPCONTEXT_CHART_RESOLUTION );\n if ( tmp != null && tmp instanceof Number )\n {\n resolution = ( (Number) tmp ).intValue( );\n if ( resolution < 96 )\n {\n resolution = 96;\n }\n }\n }\n if ( 0 == resolution )\n {\n if ( isForPrinting( ) )\n {\n resolution = 192;\n }\n else\n {\n resolution = 96;\n }\n }\n itemPresentation.setResolution( resolution );\n itemPresentation.setLocale( locale );\n String supportedImageFormats = \"PNG;GIF;JPG;BMP;\"; //$NON-NLS-1$\n IRenderOption renderOption = context.getRenderOption( );\n String formats = renderOption.getSupportedImageFormats( );\n if ( formats != null )\n {\n supportedImageFormats = formats;\n }\n itemPresentation.setSupportedImageFormats( supportedImageFormats ); // Default\n itemPresentation.setActionHandler( context.getActionHandler( ) );\n // value\n String outputFormat = getOutputFormat( );\n itemPresentation.setOutputFormat( outputFormat );\n Object rawValue = content.getRawValue( );\n if ( rawValue instanceof byte[] )\n {\n byte[] values = (byte[]) rawValue;\n itemPresentation\n .deserialize( new ByteArrayInputStream( values ) );\n }\n IRowSet[] rowSets = null;\n IBaseResultSet[] rsets = context.getResultSets();\n if ( queries == null )\n {\n DesignElementHandle elementHandle = design.getHandle( );\n if ( elementHandle instanceof ReportElementHandle )\n {\n queries = (IBaseQueryDefinition[]) context.getRunnable( )\n .getReportIR( ).getQueryByReportHandle(\n (ReportElementHandle) elementHandle );\n }\n }\n if ( queries != null )\n {\n if ( rsets != null )\n {\n rowSets = new IRowSet[rsets.length];\n for ( int i = 0; i < rowSets.length; i++ )\n {\n rowSets[i] = new RowSet( context,\n (IQueryResultSet) rsets[i] );\n }\n }\n }\n else\n {\n if ( rsets != null )\n {\n rowSets = new IRowSet[1];\n rowSets[0] = new SingleRowSet( context,\n (IQueryResultSet) rsets[0] );\n }\n }\n try\n {\n Object output = itemPresentation.onRowSets( rowSets );\n if ( output != null )\n {\n int type = itemPresentation.getOutputType( );\n String imageMIMEType = itemPresentation.getImageMIMEType( );\n generatedContent = processExtendedContent( content, type, output, imageMIMEType );\n }\n itemPresentation.finish( );\n }\n catch ( BirtException ex )\n {\n context.addException( design.getHandle( ), ex );\n logger.log( Level.SEVERE, ex.getMessage( ), ex );\n }\n }\n return generatedContent;\n }\n protected IContent processExtendedContent( IForeignContent content, int type,\n Object output, String imageMIMEType )\n {\n assert IForeignContent.EXTERNAL_TYPE.equals( content.getRawType( ) );\n assert output != null;\n IReportContent reportContent = getReportContent( );\n switch ( type )\n {\n case IReportItemPresentation.OUTPUT_NONE :\n break;\n case IReportItemPresentation.OUTPUT_AS_IMAGE :\n case IReportItemPresentation.OUTPUT_AS_IMAGE_WITH_MAP :\n // the output object is a image, so create a image content\n // object\n Object imageMap = null;\n byte[] imageContent = new byte[0];\n Object image = output;\n if ( type == IReportItemPresentation.OUTPUT_AS_IMAGE_WITH_MAP )\n {\n // OUTPUT_AS_IMAGE_WITH_MAP\n Object[] imageWithMap = (Object[]) output;\n if ( imageWithMap.length > 0 )\n {\n image = imageWithMap[0];\n }\n if ( imageWithMap.length > 1 )\n {\n imageMap = imageWithMap[1];\n }\n }\n if ( image instanceof InputStream )\n {\n imageContent = readContent( (InputStream) image );\n }\n else if ( output instanceof byte[] )\n {\n imageContent = (byte[]) image;\n }\n else\n {\n assert false;\n logger.log( Level.WARNING,\n \"unsupported image type:{0}\", output ); //$NON-NLS-1$\n }\n IImageContent imageObj = reportContent.createImageContent( content );\n imageObj.setParent( content.getParent( ) );\n // Set image map\n imageObj.setImageSource( IImageContent.IMAGE_EXPRESSION );\n imageObj.setData( imageContent );\n imageObj.setImageMap( imageMap );\n imageObj.setMIMEType( imageMIMEType );\n imageObj.setAltText( content.getAltText( ) );\n imageObj.setAltTextKey( content.getAltTextKey( ) );\n processImage( imageObj );\n return imageObj;\n case IReportItemPresentation.OUTPUT_AS_CUSTOM :\n IDataContent dataObj = reportContent.createDataContent( content );\n dataObj.setValue( output );\n processData( dataObj );\n return dataObj;\n case IReportItemPresentation.OUTPUT_AS_HTML_TEXT :\n content.setRawType( IForeignContent.HTML_TYPE );\n content.setRawValue( output.toString( ) );\n return content;\n case IReportItemPresentation.OUTPUT_AS_TEXT :\n ITextContent textObj = reportContent.createTextContent( );\n textObj.setText( output.toString( ) );\n return textObj;\n default :\n assert false;\n logger.log( Level.WARNING, \"unsupported output format:{0}\", //$NON-NLS-1$\n new Integer( type ) );\n }\n return content;\n }\n /**\n * read the content of input stream.\n *\n * @param in\n * input content\n * @return content in the stream.\n */\n static protected byte[] readContent( InputStream in )\n {\n BufferedInputStream bin = in instanceof BufferedInputStream\n ? (BufferedInputStream) in\n : new BufferedInputStream( in );\n ByteArrayOutputStream out = new ByteArrayOutputStream( 1024 );\n byte[] buffer = new byte[1024];\n int readSize = 0;\n try\n {\n readSize = bin.read( buffer );\n while ( readSize != -1 )\n {\n out.write( buffer, 0, readSize );\n readSize = bin.read( buffer );\n }\n }\n catch ( IOException ex )\n {\n logger.log( Level.SEVERE, ex.getMessage( ), ex );\n }\n return out.toByteArray( );\n }\n protected void handleOnRender( IContent content )\n {\n if ( content.getGenerateBy( ) != null )\n {\n onRenderVisitor.onRender( content );\n }\n }\n}"}}},{"rowIdx":1275,"cells":{"answer":{"kind":"string","value":"package org.cyclops.integrateddynamics.part.aspect.write;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\nimport net.minecraft.block.state.IBlockState;\nimport net.minecraft.init.SoundEvents;\nimport net.minecraft.item.ItemStack;\nimport net.minecraft.util.SoundCategory;\nimport net.minecraft.util.SoundEvent;\nimport net.minecraft.util.math.BlockPos;\nimport net.minecraft.world.World;\nimport net.minecraftforge.event.world.NoteBlockEvent;\nimport net.minecraftforge.fluids.FluidStack;\nimport org.apache.commons.lang3.tuple.Pair;\nimport org.apache.commons.lang3.tuple.Triple;\nimport org.cyclops.integrateddynamics.api.evaluate.EvaluationException;\nimport org.cyclops.integrateddynamics.api.evaluate.variable.IValue;\nimport org.cyclops.integrateddynamics.api.evaluate.variable.IValueType;\nimport org.cyclops.integrateddynamics.api.evaluate.variable.IVariable;\nimport org.cyclops.integrateddynamics.api.part.PartTarget;\nimport org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;\nimport org.cyclops.integrateddynamics.api.part.aspect.property.IAspectPropertyTypeInstance;\nimport org.cyclops.integrateddynamics.api.part.write.IPartStateWriter;\nimport org.cyclops.integrateddynamics.api.part.write.IPartTypeWriter;\nimport org.cyclops.integrateddynamics.core.evaluate.variable.*;\nimport org.cyclops.integrateddynamics.core.part.aspect.build.AspectBuilder;\nimport org.cyclops.integrateddynamics.core.part.aspect.build.IAspectValuePropagator;\nimport org.cyclops.integrateddynamics.core.part.aspect.build.IAspectWriteDeactivator;\nimport org.cyclops.integrateddynamics.core.part.aspect.property.AspectProperties;\nimport org.cyclops.integrateddynamics.core.part.aspect.property.AspectPropertyTypeInstance;\nimport org.cyclops.integrateddynamics.part.aspect.read.AspectReadBuilders;\nimport org.cyclops.integrateddynamics.part.aspect.write.redstone.IWriteRedstoneComponent;\nimport org.cyclops.integrateddynamics.part.aspect.write.redstone.WriteRedstoneComponent;\nimport java.util.List;\n/**\n * Collection of aspect write builders and value propagators.\n * @author rubensworks\n */\npublic class AspectWriteBuilders {\n public static final AspectBuilder>\n BUILDER_BOOLEAN = getValue(AspectBuilder.forWriteType(ValueTypes.BOOLEAN));\n public static final AspectBuilder>\n BUILDER_INTEGER = getValue(AspectBuilder.forWriteType(ValueTypes.INTEGER));\n public static final AspectBuilder>\n BUILDER_DOUBLE = getValue(AspectBuilder.forWriteType(ValueTypes.DOUBLE));\n public static final AspectBuilder>\n BUILDER_STRING = getValue(AspectBuilder.forWriteType(ValueTypes.STRING));\n public static final AspectBuilder>\n BUILDER_LIST = getValue(AspectBuilder.forWriteType(ValueTypes.LIST));\n public static final AspectBuilder>\n BUILDER_ITEMSTACK = getValue(AspectBuilder.forWriteType(ValueTypes.OBJECT_ITEMSTACK));\n public static final AspectBuilder>\n BUILDER_FLUIDSTACK = getValue(AspectBuilder.forWriteType(ValueTypes.OBJECT_FLUIDSTACK));\n public static final AspectBuilder>\n BUILDER_OPERATOR = getValue(AspectBuilder.forWriteType(ValueTypes.OPERATOR));\n public static final IAspectValuePropagator, Triple> PROP_GET_BOOLEAN = new IAspectValuePropagator, Triple>() {\n @Override\n public Triple getOutput(Triple input) throws EvaluationException {\n return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue());\n }\n };\n public static final IAspectValuePropagator, Triple> PROP_GET_INTEGER = new IAspectValuePropagator, Triple>() {\n @Override\n public Triple getOutput(Triple input) throws EvaluationException {\n return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue());\n }\n };\n public static final IAspectValuePropagator, Triple> PROP_GET_DOUBLE = new IAspectValuePropagator, Triple>() {\n @Override\n public Triple getOutput(Triple input) throws EvaluationException {\n return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue());\n }\n };\n public static final IAspectValuePropagator, Triple> PROP_GET_LONG = new IAspectValuePropagator, Triple>() {\n @Override\n public Triple getOutput(Triple input) throws EvaluationException {\n return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue());\n }\n };\n public static final IAspectValuePropagator, Triple> PROP_GET_ITEMSTACK = new IAspectValuePropagator, Triple>() {\n @Override\n public Triple getOutput(Triple input) throws EvaluationException {\n ItemStack optional = input.getRight().getRawValue();\n return Triple.of(input.getLeft(), input.getMiddle(), !optional.isEmpty() ? optional : null);\n }\n };\n public static final IAspectValuePropagator, Triple> PROP_GET_STRING = new IAspectValuePropagator, Triple>() {\n @Override\n public Triple getOutput(Triple input) throws EvaluationException {\n return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue());\n }\n };\n public static final IAspectValuePropagator, Triple> PROP_GET_BLOCK = new IAspectValuePropagator, Triple>() {\n @Override\n public Triple getOutput(Triple input) throws EvaluationException {\n Optional optional = input.getRight().getRawValue();\n return Triple.of(input.getLeft(), input.getMiddle(), optional.isPresent() ? optional.get() : null);\n }\n };\n public static final IAspectValuePropagator, Triple> PROP_GET_FLUIDSTACK = new IAspectValuePropagator, Triple>() {\n @Override\n public Triple getOutput(Triple input) throws EvaluationException {\n Optional optional = input.getRight().getRawValue();\n return Triple.of(input.getLeft(), input.getMiddle(), optional.isPresent() ? optional.get() : null);\n }\n };\n public static final class Audio {\n public static final IAspectPropertyTypeInstance PROP_VOLUME =\n new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, \"aspect.aspecttypes.integrateddynamics.double.volume.name\", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);\n public static final IAspectPropertyTypeInstance PROP_FREQUENCY =\n new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, \"aspect.aspecttypes.integrateddynamics.double.frequency.name\", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);\n public static final IAspectProperties PROPERTIES_NOTE = new AspectProperties(Sets.newHashSet(\n PROP_VOLUME\n ));\n public static final IAspectProperties PROPERTIES_SOUND = new AspectProperties(ImmutableList.of(\n PROP_VOLUME,\n PROP_FREQUENCY\n ));\n static {\n Predicate POSITIVE = new Predicate() {\n @Override\n public boolean apply(ValueTypeDouble.ValueDouble input) {\n return input.getRawValue() >= 0;\n }\n };\n PROPERTIES_NOTE.setValue(PROP_VOLUME, ValueTypeDouble.ValueDouble.of(3D));\n PROPERTIES_SOUND.setValue(PROP_VOLUME, ValueTypeDouble.ValueDouble.of(3D));\n PROPERTIES_SOUND.setValue(PROP_FREQUENCY, ValueTypeDouble.ValueDouble.of(1D));\n }\n private static final List INSTRUMENTS = Lists.newArrayList(new SoundEvent[] {SoundEvents.BLOCK_NOTE_HARP, SoundEvents.BLOCK_NOTE_BASEDRUM, SoundEvents.BLOCK_NOTE_SNARE, SoundEvents.BLOCK_NOTE_HAT, SoundEvents.BLOCK_NOTE_BASS});\n private static SoundEvent getInstrument(int id) {\n if (id < 0 || id >= INSTRUMENTS.size()) {\n id = 0;\n }\n return INSTRUMENTS.get(id);\n }\n public static final IAspectValuePropagator>, Void> PROP_SET = new IAspectValuePropagator>, Void>() {\n @Override\n public Void getOutput(Triple> input) {\n IAspectProperties properties = input.getMiddle();\n BlockPos pos = input.getLeft().getTarget().getPos().getBlockPos();\n int eventID = input.getRight().getLeft().ordinal();\n int eventParam = input.getRight().getRight();\n if(eventParam >= 0 && eventParam <= 24) {\n World world = input.getLeft().getTarget().getPos().getWorld();\n NoteBlockEvent.Play e = new NoteBlockEvent.Play(world, pos, world.getBlockState(pos), eventParam, eventID);\n if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(e)) {\n float f = (float) Math.pow(2.0D, (double) (eventParam - 12) / 12.0D);\n float volume = (float) properties.getValue(PROP_VOLUME).getRawValue();\n world.playSound(null,\n (double) pos.getX() + 0.5D, (double) pos.getY() + 0.5D, (double) pos.getZ() + 0.5D,\n getInstrument(eventID), SoundCategory.RECORDS, volume, f);\n }\n }\n return null;\n }\n };\n public static IAspectValuePropagator, Triple>>\n propWithInstrument(final NoteBlockEvent.Instrument instrument) {\n return new IAspectValuePropagator, Triple>>() {\n @Override\n public Triple> getOutput(Triple input) throws EvaluationException {\n return Triple.of(input.getLeft(), input.getMiddle(), Pair.of(instrument, input.getRight()));\n }\n };\n }\n public static final AspectBuilder>\n BUILDER_INTEGER = AspectWriteBuilders.BUILDER_INTEGER.appendKind(\"audio\").handle(PROP_GET_INTEGER);\n public static final AspectBuilder>\n BUILDER_INTEGER_INSTRUMENT = BUILDER_INTEGER.appendKind(\"instrument\").withProperties(PROPERTIES_NOTE);\n public static final AspectBuilder>\n BUILDER_STRING = AspectWriteBuilders.BUILDER_STRING.appendKind(\"audio\").handle(PROP_GET_STRING);\n }\n public static final class Effect {\n public static final IAspectPropertyTypeInstance PROP_OFFSET_X =\n new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, \"aspect.aspecttypes.integrateddynamics.double.offset_x.name\", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);\n public static final IAspectPropertyTypeInstance PROP_OFFSET_Y =\n new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, \"aspect.aspecttypes.integrateddynamics.double.offset_y.name\", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);\n public static final IAspectPropertyTypeInstance PROP_OFFSET_Z =\n new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, \"aspect.aspecttypes.integrateddynamics.double.offset_z.name\", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);\n public static final IAspectPropertyTypeInstance PROP_PARTICLES =\n new AspectPropertyTypeInstance<>(ValueTypes.INTEGER, \"aspect.aspecttypes.integrateddynamics.integer.particles.name\", AspectReadBuilders.VALIDATOR_INTEGER_POSITIVE);\n public static final IAspectPropertyTypeInstance PROP_SPREAD_X =\n new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, \"aspect.aspecttypes.integrateddynamics.double.spread_x.name\", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);\n public static final IAspectPropertyTypeInstance PROP_SPREAD_Y =\n new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, \"aspect.aspecttypes.integrateddynamics.double.spread_y.name\", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);\n public static final IAspectPropertyTypeInstance PROP_SPREAD_Z =\n new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, \"aspect.aspecttypes.integrateddynamics.double.spread_z.name\", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);\n public static final IAspectPropertyTypeInstance PROP_FORCE =\n new AspectPropertyTypeInstance<>(ValueTypes.BOOLEAN, \"aspect.aspecttypes.integrateddynamics.boolean.force_particle.name\");\n public static final IAspectProperties PROPERTIES_PARTICLE = new AspectProperties(ImmutableList.of(\n PROP_OFFSET_X,\n PROP_OFFSET_Y,\n PROP_OFFSET_Z,\n PROP_PARTICLES,\n PROP_SPREAD_X,\n PROP_SPREAD_Y,\n PROP_SPREAD_Z,\n PROP_FORCE\n ));\n static {\n PROPERTIES_PARTICLE.setValue(PROP_OFFSET_X, ValueTypeDouble.ValueDouble.of(0.5D));\n PROPERTIES_PARTICLE.setValue(PROP_OFFSET_Z, ValueTypeDouble.ValueDouble.of(0.5D));\n PROPERTIES_PARTICLE.setValue(PROP_OFFSET_Y, ValueTypeDouble.ValueDouble.of(0.5D));\n PROPERTIES_PARTICLE.setValue(PROP_PARTICLES, ValueTypeInteger.ValueInteger.of(1));\n PROPERTIES_PARTICLE.setValue(PROP_SPREAD_X, ValueTypeDouble.ValueDouble.of(0.0D));\n PROPERTIES_PARTICLE.setValue(PROP_SPREAD_Y, ValueTypeDouble.ValueDouble.of(0.0D));\n PROPERTIES_PARTICLE.setValue(PROP_SPREAD_Z, ValueTypeDouble.ValueDouble.of(0.0D));\n PROPERTIES_PARTICLE.setValue(PROP_FORCE, ValueTypeBoolean.ValueBoolean.of(false));\n }\n public static final AspectBuilder>\n BUILDER_DOUBLE = AspectWriteBuilders.BUILDER_DOUBLE.appendKind(\"effect\").handle(PROP_GET_DOUBLE);\n public static final AspectBuilder>\n BUILDER_DOUBLE_PARTICLE = BUILDER_DOUBLE.withProperties(PROPERTIES_PARTICLE);\n }\n public static final class Redstone {\n private static final IWriteRedstoneComponent WRITE_REDSTONE_COMPONENT = new WriteRedstoneComponent();\n public static final IAspectValuePropagator, Void> PROP_SET = new IAspectValuePropagator, Void>() {\n @Override\n public Void getOutput(Triple input) {\n boolean strongPower = input.getMiddle().getValue(PROP_STRONG_POWER).getRawValue();\n WRITE_REDSTONE_COMPONENT.setRedstoneLevel(input.getLeft(), input.getRight(), strongPower);\n return null;\n }\n };\n public static final IAspectWriteDeactivator DEACTIVATOR = new IAspectWriteDeactivator() {\n @Override\n public

    , S extends IPartStateWriter

    > void onDeactivate(P partType, PartTarget target, S state) {\n WRITE_REDSTONE_COMPONENT.deactivate(target);\n }\n };\n public static final IAspectPropertyTypeInstance PROP_STRONG_POWER =\n new AspectPropertyTypeInstance<>(ValueTypes.BOOLEAN, \"aspect.aspecttypes.integrateddynamics.boolean.strong_power.name\");\n public static final IAspectProperties PROPERTIES_REDSTONE = new AspectProperties(ImmutableList.of(\n PROP_STRONG_POWER\n ));\n static {\n PROPERTIES_REDSTONE.setValue(PROP_STRONG_POWER, ValueTypeBoolean.ValueBoolean.of(false));\n }\n public static final AspectBuilder>\n BUILDER_BOOLEAN = AspectWriteBuilders.BUILDER_BOOLEAN.appendKind(\"redstone\").handle(PROP_GET_BOOLEAN).appendDeactivator(DEACTIVATOR).withProperties(PROPERTIES_REDSTONE);\n public static final AspectBuilder>\n BUILDER_INTEGER = AspectWriteBuilders.BUILDER_INTEGER.appendKind(\"redstone\").handle(PROP_GET_INTEGER).appendDeactivator(DEACTIVATOR).withProperties(PROPERTIES_REDSTONE);\n }\n public static > AspectBuilder> getValue(AspectBuilder>> builder) {\n return builder.handle(new IAspectValuePropagator>, Triple>() {\n @Override\n public Triple getOutput(Triple> input) throws EvaluationException {\n return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getValue());\n }\n });\n }\n}"}}},{"rowIdx":1276,"cells":{"answer":{"kind":"string","value":"package org.wikipathways.wp2rdf;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Collections;\nimport org.bridgedb.DataSource;\nimport org.bridgedb.IDMapperException;\nimport org.bridgedb.IDMapperStack;\nimport org.bridgedb.bio.DataSourceTxt;\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.pathvisio.core.model.ConverterException;\nimport org.pathvisio.core.model.Pathway;\nimport org.wikipathways.wp2rdf.io.PathwayReader;\npublic abstract class AbstractWPConvertorTest extends AbstractConvertorTest {\n public static void loadModelAsWPRDF(String gpmlFile, String wpid, String revision) throws ConverterException, FileNotFoundException, ClassNotFoundException, IOException, IDMapperException {\n DataSourceTxt.init();\n // the next line is needed until BridgeDb gets updated\n DataSource.register(\"Cpx\", \"Complex Portal\")\n .identifiersOrgBase(\"http://identifiers.org/complexportal/\")\n .asDataSource();\n DataSource.register(\"Pbd\", \"Digital Object Identifier\").asDataSource();\n DataSource.register(\"Pbm\", \"PubMed\").asDataSource();\n DataSource.register(\"Gpl\", \"Guide to Pharmacology Targets\").asDataSource();\n InputStream input = AbstractConvertorTest.class.getClassLoader().getResourceAsStream(gpmlFile);\n Pathway pathway = PathwayReader.readPathway(input);\n Assert.assertNotNull(pathway);\n IDMapperStack stack = WPREST2RDF.maps();\n model = GpmlConverter.convertWp(pathway, wpid, revision, stack, Collections.emptyList());\n Assert.assertNotNull(model);\n // String ttlContent = toString(model);\n // if (ttlContent.length() > 1000) ttlContent.substring(0,1000);\n // System.out.println(ttlContent);\n }\n @Test\n public void untypedPubMedRef() throws Exception {\n String sparql = ResourceHelper.resourceAsString(\"structure/untypedPubMedRefs.rq\");\n StringMatrix table = SPARQLHelper.sparql(model, sparql);\n Assert.assertNotNull(table);\n Assert.assertEquals(\"No tping as wp:PublicationReference for PubMed URIs:\\n\" + table, 0, table.getRowCount());\n }\n}"}}},{"rowIdx":1277,"cells":{"answer":{"kind":"string","value":"package org.jivesoftware.smackx;\nimport java.util.*;\nimport org.jivesoftware.smack.packet.*;\nimport org.jivesoftware.smackx.packet.DataForm;\n/**\n * Represents a Form for gathering data. The form could be of the following types:\n *

      \n *
    • form -> Indicates a form to fill out.
    • \n *
    • submit -> The form is filled out, and this is the data that is being returned from\n * the form.
    • \n *
    • cancel -> The form was cancelled. Tell the asker that piece of information.
    • \n *
    • result -> Data results being returned from a search, or some other query.
    • \n *
    \n *\n * Depending of the form's type different operations are available. For example, it's only possible\n * to set answers if the form is of type \"submit\".\n *\n * @author Gaston Dombiak\n */\npublic class Form {\n public static final String TYPE_FORM = \"form\";\n public static final String TYPE_SUBMIT = \"submit\";\n public static final String TYPE_CANCEL = \"cancel\";\n public static final String TYPE_RESULT = \"result\";\n private DataForm dataForm;\n /**\n * Returns a new ReportedData if the packet is used for gathering data and includes an\n * extension that matches the elementName and namespace \"x\",\"jabber:x:data\".\n *\n * @param packet the packet used for gathering data.\n */\n public static Form getFormFrom(Packet packet) {\n // Check if the packet includes the DataForm extension\n PacketExtension packetExtension = packet.getExtension(\"x\",\"jabber:x:data\");\n if (packetExtension != null) {\n // Check if the existing DataForm is not a result of a search\n DataForm dataForm = (DataForm) packetExtension;\n if (dataForm.getReportedData() == null)\n return new Form(dataForm);\n }\n // Otherwise return null\n return null;\n }\n /**\n * Creates a new Form that will wrap an existing DataForm. The wrapped DataForm must be\n * used for gathering data.\n *\n * @param dataForm the data form used for gathering data.\n */\n private Form(DataForm dataForm) {\n this.dataForm = dataForm;\n }\n /**\n * Creates a new Form of a given type from scratch.

    \n *\n * Possible form types are:\n *

      \n *
    • form -> Indicates a form to fill out.
    • \n *
    • submit -> The form is filled out, and this is the data that is being returned from\n * the form.
    • \n *
    • cancel -> The form was cancelled. Tell the asker that piece of information.
    • \n *
    • result -> Data results being returned from a search, or some other query.
    • \n *
    \n *\n * @param type the form's type (e.g. form, submit,cancel,result).\n */\n public Form(String type) {\n this.dataForm = new DataForm(type);\n }\n /**\n * Adds a new field to complete as part of the form.\n *\n * @param field the field to complete.\n */\n public void addField(FormField field) {\n dataForm.addField(field);\n }\n public void setAnswer(String variable, String value) {\n if (!isSubmitType()) {\n throw new IllegalStateException(\"Cannot set an answer if the form is not of type \" +\n \"\\\"submit\\\"\");\n }\n FormField field = getField(variable);\n if (field != null) {\n field.resetValues();\n field.addValue(value);\n }\n else {\n throw new IllegalArgumentException(\"Couldn't find a field for the specified variable.\");\n }\n }\n public void setAnswer(String variable, List values) {\n if (!isSubmitType()) {\n throw new IllegalStateException(\"Cannot set an answer if the form is not of type \" +\n \"\\\"submit\\\"\");\n }\n FormField field = getField(variable);\n if (field != null) {\n field.resetValues();\n field.addValues(values);\n }\n else {\n throw new IllegalArgumentException(\"Couldn't find a field for the specified variable.\");\n }\n }\n /**\n * Returns an Iterator for the fields that are part of the form.\n *\n * @return an Iterator for the fields that are part of the form.\n */\n public Iterator getFields() {\n return dataForm.getFields();\n }\n /**\n * Returns the field of the form whose variable matches the specified variable.\n * The fields of type FIXED will never be returned since they do not specify a\n * variable.\n *\n * @param variable the variable to look for in the form fields.\n * @return the field of the form whose variable matches the specified variable.\n */\n public FormField getField(String variable) {\n if (variable == null || variable.equals(\"\")) {\n throw new IllegalArgumentException(\"Variable must not be null or blank.\");\n }\n // Look for the field whose variable matches the requested variable\n FormField field;\n for (Iterator it=getFields();it.hasNext();) {\n field = (FormField)it.next();\n if (variable.equals(field.getVariable())) {\n return field;\n }\n }\n return null;\n }\n /**\n * Returns the instructions that explain how to fill out the form and what the form is about.\n *\n * @return instructions that explain how to fill out the form.\n */\n public String getInstructions() {\n return dataForm.getInstructions();\n }\n /**\n * Returns the description of the data. It is similar to the title on a web page or an X\n * window. You can put a on either a form to fill out, or a set of data results.\n *\n * @return description of the data.\n */\n public String getTitle() {\n return dataForm.getTitle();\n }\n /**\n * Returns the meaning of the data within the context. The data could be part of a form\n * to fill out, a form submission or data results.<p>\n *\n * Possible form types are:\n * <ul>\n * <li>form -> Indicates a form to fill out.</li>\n * <li>submit -> The form is filled out, and this is the data that is being returned from\n * the form.</li>\n * <li>cancel -> The form was cancelled. Tell the asker that piece of information.</li>\n * <li>result -> Data results being returned from a search, or some other query.</li>\n * </ul>\n *\n * @return the form's type.\n */\n public String getType() {\n return dataForm.getType();\n }\n /**\n * Sets instructions that explain how to fill out the form and what the form is about.\n *\n * @param instructions instructions that explain how to fill out the form.\n */\n public void setInstructions(String instructions) {\n dataForm.setInstructions(instructions);\n }\n /**\n * Sets the description of the data. It is similar to the title on a web page or an X window.\n * You can put a <title/> on either a form to fill out, or a set of data results.\n *\n * @param title description of the data.\n */\n public void setTitle(String title) {\n dataForm.setTitle(title);\n }\n /**\n * Returns a DataForm that serves to send this Form to the server. If the form is of type\n * submit, it may contain fields with no value. These fields will be remove since they only\n * exist to assist the user while editing/completing the form in a UI.\n *\n * @return the wrapped DataForm.\n */\n DataForm getDataFormToSend() {\n if (isSubmitType()) {\n // Answer a new form based on the values of this form\n DataForm dataFormToSend = new DataForm(getType());\n dataFormToSend.setInstructions(getInstructions());\n dataFormToSend.setTitle(getTitle());\n // Remove all the fields that have no answer\n for(Iterator it=getFields();it.hasNext();) {\n FormField field = (FormField)it.next();\n if (field.getValues().hasNext()) {\n dataFormToSend.addField(field);\n }\n }\n return dataFormToSend;\n }\n return dataForm;\n }\n /**\n * Returns true if the form is a form to fill out.\n *\n * @return if the form is a form to fill out.\n */\n private boolean isFormType() {\n return TYPE_FORM.equals(dataForm.getType());\n }\n /**\n * Returns true if the form is a form to submit.\n *\n * @return if the form is a form to submit.\n */\n private boolean isSubmitType() {\n return TYPE_SUBMIT.equals(dataForm.getType());\n }\n /**\n * Returns a new Form to submit the completed values. The new Form will include all the fields\n * of the original form except for the fields of type FIXED. Only the HIDDEN fields will\n * include the same value of the original form. The other fields of the new form MUST be\n * completed. If a field remains with no answer when sending the completed form, then it won't\n * be included as part of the completed form.<p>\n *\n * The reason why the fields with variables are included in the new form is to provide a model\n * for binding with any UI. This means that the UIs will use the original form (of type\n * \"form\") to learn how to render the form, but the UIs will bind the fields to the form of\n * type submit.\n *\n * @return a Form to submit the completed values.\n */\n public Form createAnswerForm() {\n if (!isFormType()) {\n throw new IllegalStateException(\"Only forms of type \\\"form\\\" could be answered\");\n }\n // Create a new Form\n Form form = new Form(TYPE_SUBMIT);\n for (Iterator fields=getFields(); fields.hasNext();) {\n FormField field = (FormField)fields.next();\n // Add to the new form any type of field that includes a variable.\n // Note: The fields of type FIXED are the only ones that don't specify a variable\n if (field.getVariable() != null) {\n form.addField(new FormField(field.getVariable()));\n // Set the answer ONLY to the hidden fields\n if (FormField.TYPE_HIDDEN.equals(field.getType())) {\n // Since a hidden field could have many values we need to collect them\n // in a list\n List values = new ArrayList();\n for (Iterator it=field.getValues();it.hasNext();) {\n values.add((String)it.next());\n }\n form.setAnswer(field.getVariable(), values);\n }\n }\n }\n return form;\n }\n}"}}},{"rowIdx":1278,"cells":{"answer":{"kind":"string","value":"package ru.tuin;\n/**\n * @author Viktor Tulin\n * @version 1\n * @since 27.10.2016\n */\npublic class StartUI {\n private Calculator calc;\n private ConsoleInput input;\n private InteractCalculator menu;\n public StartUI(ConsoleInput input, Calculator calc, InteractCalculator menu) {\n this.calc = calc;\n this.input = input;\n this.menu = menu;\n }\n /**\n * method displays a menu until the user does not want to leave the program\n */\n public void init() {\n do {\n menu.show();\n int entry = this.input.ask(\"\\nselect the menu item: \", menu.getAcceptableRange());\n menu.select(Key.getKeyFromNumber(entry));\n } while (!\"y\".equals(this.input.ask(\"To exit the program press (y) To continue work press (Enter): \")));\n }\n public static void main(String[] args) {\n EngineerCalculator calc = new EngineerCalculator();\n ConsoleInput input = new ValidateInput();\n Print print = new Print();\n EngineerInteractCalculator menu = new EngineerInteractCalculator(input, calc, print);\n new StartUI(input, calc, menu).init();\n }\n}"}}},{"rowIdx":1279,"cells":{"answer":{"kind":"string","value":"package org.cyclops.structuredcrafting.craft.provider;\nimport com.mojang.authlib.GameProfile;\nimport net.minecraft.core.BlockPos;\nimport net.minecraft.core.Direction;\nimport net.minecraft.server.level.ServerLevel;\nimport net.minecraft.world.item.BlockItem;\nimport net.minecraft.world.item.ItemStack;\nimport net.minecraft.world.level.Level;\nimport net.minecraft.world.level.block.state.BlockState;\nimport net.minecraft.world.phys.BlockHitResult;\nimport net.minecraft.world.phys.Vec3;\nimport net.minecraftforge.common.util.FakePlayer;\nimport net.minecraftforge.items.CapabilityItemHandler;\nimport net.minecraftforge.items.IItemHandler;\nimport org.cyclops.cyclopscore.helper.BlockEntityHelpers;\nimport org.cyclops.cyclopscore.helper.ItemStackHelpers;\nimport org.cyclops.structuredcrafting.block.BlockStructuredCrafterConfig;\nimport java.util.Map;\nimport java.util.UUID;\nimport java.util.WeakHashMap;\n/**\n * World that can provide an itemstack.\n * @author rubensworks\n */\npublic class WorldItemStackProvider implements IItemStackProvider {\n private static GameProfile PROFILE = new GameProfile(UUID.fromString(\"41C82C87-7AfB-4024-BB57-13D2C99CAE78\"), \"[StructuredCrafting]\");\n private static final Map<ServerLevel, FakePlayer> FAKE_PLAYERS = new WeakHashMap<ServerLevel, FakePlayer>();\n public static FakePlayer getFakePlayer(ServerLevel world) {\n FakePlayer fakePlayer = FAKE_PLAYERS.get(world);\n if (fakePlayer == null) {\n fakePlayer = new FakePlayer(world, PROFILE);\n FAKE_PLAYERS.put(world, fakePlayer);\n }\n return fakePlayer;\n }\n @Override\n public boolean canProvideInput() {\n return BlockStructuredCrafterConfig.canTakeInputsFromWorld;\n }\n @Override\n public boolean canHandleOutput() {\n return BlockStructuredCrafterConfig.canPlaceOutputsIntoWorld;\n }\n @Override\n public boolean isValidForResults(Level world, BlockPos pos, Direction side) {\n return world.isEmptyBlock(pos);\n }\n protected boolean hasEmptyItemHandler(Level world, BlockPos pos, Direction side) {\n IItemHandler itemHandler = BlockEntityHelpers.getCapability(world, pos, side, CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).orElse(null);\n boolean emptyItemHandler = true;\n if (itemHandler != null) {\n for (int i = 0; i < itemHandler.getSlots(); i++) {\n if (!itemHandler.extractItem(i, 1, true).isEmpty()) {\n emptyItemHandler = false;\n break;\n }\n }\n }\n return emptyItemHandler;\n }\n @Override\n public boolean hasItemStack(Level world, BlockPos pos, Direction side) {\n return !world.isEmptyBlock(pos) && hasEmptyItemHandler(world, pos, side);\n }\n @Override\n public ItemStack getItemStack(Level world, BlockPos pos, Direction side) {\n BlockState blockState = world.getBlockState(pos);\n if(blockState != null && hasEmptyItemHandler(world, pos, side)) {\n return blockState.getCloneItemStack(new BlockHitResult(new Vec3(0, 0, 0), side, pos, false), world, pos, getFakePlayer((ServerLevel) world));\n }\n return ItemStack.EMPTY;\n }\n @Override\n public void reduceItemStack(Level world, BlockPos pos, Direction side, boolean simulate) {\n if(!simulate) {\n world.removeBlock(pos, false);\n }\n }\n @Override\n public boolean addItemStack(Level world, BlockPos pos, Direction side, ItemStack itemStack, boolean simulate) {\n return setItemStack(world, pos, side, itemStack, simulate);\n }\n @Override\n public boolean setItemStack(Level world, BlockPos pos, Direction side, ItemStack itemStack, boolean simulate) {\n if(!simulate && itemStack.getItem() instanceof BlockItem) {\n world.setBlockAndUpdate(pos, ((BlockItem) itemStack.getItem()).getBlock().defaultBlockState());\n itemStack.shrink(1);\n }\n if(!simulate && itemStack.getCount() > 0) {\n ItemStackHelpers.spawnItemStack(world, pos, itemStack);\n }\n return true;\n }\n}"}}},{"rowIdx":1280,"cells":{"answer":{"kind":"string","value":"package de.vanmar.android.yarrn.requests;\nimport android.app.Application;\nimport com.octo.android.robospice.persistence.DurationInMillis;\nimport com.octo.android.robospice.persistence.exception.SpiceException;\nimport com.octo.android.robospice.persistence.springandroid.json.gson.GsonObjectPersisterFactory;\nimport org.acra.ACRA;\nimport org.scribe.model.OAuthRequest;\nimport org.scribe.model.Response;\nimport de.vanmar.android.yarrn.YarrnPrefs_;\nimport de.vanmar.android.yarrn.ravelry.dts.ETaggable;\npublic abstract class AbstractRavelryGetRequest<T extends ETaggable> extends AbstractRavelryRequest<T> {\n public static final long CACHE_DURATION = DurationInMillis.ONE_MINUTE;\n private final GsonObjectPersisterFactory persisterFactory;\n public AbstractRavelryGetRequest(Class<T> clazz, Application application, YarrnPrefs_ prefs) {\n super(clazz, prefs, application);\n try {\n persisterFactory = new GsonObjectPersisterFactory(application);\n } catch (SpiceException e) {\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n @Override\n public T loadDataFromNetwork() throws Exception {\n final OAuthRequest request = getRequest();\n ACRA.getErrorReporter().putCustomData(\"lastUrl\", getCacheKey().toString());\n /*T dataFromCache = persisterFactory.createObjectPersister(getResultType()).loadDataFromCache(getCacheKey(), DurationInMillis.ALWAYS_RETURNED);\n if (dataFromCache != null) {\n request.addHeader(\"If-None-Match\", dataFromCache.getETag());\n }*/\n final Response response = executeRequest(request);\n /*if (response.getCode() == 304) {\n return dataFromCache;\n } else {*/\n T result = parseResult(response.getBody());\n result.setETag(response.getHeader(\"ETag\"));\n return result;\n }\n protected abstract T parseResult(String responseBody);\n protected abstract OAuthRequest getRequest();\n public Object getCacheKey() {\n OAuthRequest request = getRequest();\n return request.getCompleteUrl();\n }\n}"}}},{"rowIdx":1281,"cells":{"answer":{"kind":"string","value":"package org.jenkinsci.plugins.docker.commons.impl;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport javax.annotation.Nonnull;\nimport org.apache.commons.lang.StringUtils;\nimport org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial;\nimport org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory;\nimport org.kohsuke.accmod.Restricted;\nimport org.kohsuke.accmod.restrictions.NoExternalUse;\nimport hudson.AbortException;\nimport hudson.EnvVars;\nimport hudson.FilePath;\nimport hudson.Launcher;\nimport hudson.model.TaskListener;\nimport hudson.util.ArgumentListBuilder;\nimport net.sf.json.JSONObject;\n/**\n * Logs you in to a Docker registry.\n */\n@Restricted(NoExternalUse.class)\npublic class RegistryKeyMaterialFactory extends KeyMaterialFactory {\n private static final String DOCKER_CONFIG_FILENAME = \"config.json\";\n private static final String[] BLACKLISTED_PROPERTIES = { \"auths\", \"credsStore\" };\n private final @Nonnull String username;\n private final @Nonnull String password;\n private final @Nonnull URL endpoint;\n private final @Nonnull Launcher launcher;\n private final @Nonnull EnvVars env;\n private final @Nonnull TaskListener listener;\n private final @Nonnull String dockerExecutable;\n public RegistryKeyMaterialFactory(@Nonnull String username, @Nonnull String password, @Nonnull URL endpoint, @Nonnull Launcher launcher, @Nonnull EnvVars env, @Nonnull TaskListener listener, @Nonnull String dockerExecutable) {\n this.username = username;\n this.password = password;\n this.endpoint = endpoint;\n this.launcher = launcher;\n this.env = env;\n this.listener = listener;\n this.dockerExecutable = dockerExecutable;\n }\n @Override\n public KeyMaterial materialize() throws IOException, InterruptedException {\n FilePath dockerConfig = createSecretsDirectory();\n // read the existing docker config file, which might hold some important settings (e.b. proxies)\n FilePath configJsonPath = FilePath.getHomeDirectory(this.launcher.getChannel()).child(\".docker\").child(DOCKER_CONFIG_FILENAME);\n if (configJsonPath.exists()) {\n String configJson = configJsonPath.readToString();\n if (StringUtils.isNotBlank(configJson)) {\n launcher.getListener().getLogger().print(\"Using the existing docker config file.\");\n JSONObject json = JSONObject.fromObject(configJson);\n for (String property : BLACKLISTED_PROPERTIES) {\n Object value = json.remove(property);\n if (value != null) {\n launcher.getListener().getLogger().print(\"Removing blacklisted property: \" + property);\n }\n }\n dockerConfig.child(DOCKER_CONFIG_FILENAME).write(json.toString(), StandardCharsets.UTF_8.name());\n }\n }\n try {\n EnvVars envWithConfig = new EnvVars(env);\n envWithConfig.put(\"DOCKER_CONFIG\", dockerConfig.getRemote());\n if (launcher.launch().cmds(new ArgumentListBuilder(dockerExecutable, \"login\", \"-u\", username, \"--password-stdin\").add(endpoint)).envs(envWithConfig).stdin(new ByteArrayInputStream(password.getBytes(\"UTF-8\"))).stdout(listener).join() != 0) {\n throw new AbortException(\"docker login failed\");\n }\n } catch (IOException | InterruptedException x) {\n try {\n dockerConfig.deleteRecursive();\n } catch (Exception x2) {\n x.addSuppressed(x2);\n }\n throw x;\n }\n return new RegistryKeyMaterial(dockerConfig, new EnvVars(\"DOCKER_CONFIG\", dockerConfig.getRemote()));\n }\n private static class RegistryKeyMaterial extends KeyMaterial {\n private final FilePath dockerConfig;\n RegistryKeyMaterial(FilePath dockerConfig, EnvVars envVars) {\n super(envVars);\n this.dockerConfig = dockerConfig;\n }\n @Override\n public void close() throws IOException {\n try {\n dockerConfig.deleteRecursive();\n } catch (InterruptedException x) {\n // TODO would better have been thrown from KeyMaterial.close to begin with\n throw new IOException(x);\n }\n }\n }\n}"}}},{"rowIdx":1282,"cells":{"answer":{"kind":"string","value":"package makeithappen.vaadin.app.internal;\nimport org.eclipse.emf.ecp.makeithappen.model.task.TaskFactory;\nimport org.eclipse.emf.ecp.makeithappen.model.task.User;\nimport org.eclipse.emf.ecp.view.core.vaadin.ECPVaadinView;\nimport org.eclipse.emf.ecp.view.core.vaadin.ECPVaadinViewRenderer;\nimport org.lunifera.runtime.web.vaadin.databinding.VaadinObservables;\nimport com.vaadin.annotations.Push;\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.server.VaadinRequest;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.themes.ValoTheme;\n// @PreserveOnRefresh\n@Theme(ValoTheme.THEME_NAME)\n// @Theme(Reindeer.THEME_NAME)\n@Push\n/**\n * Render the eObject.\n * @author Dennis Melzer\n *\n */\npublic class VaadinMainUI extends UI {\n private static final long serialVersionUID = 1L;\n final static User USER = TaskFactory.eINSTANCE.createUser();\n @Override\n protected void init(VaadinRequest request) {\n getPage().setTitle(\"Test Vaadin Valo\");\n VaadinObservables.activateRealm(this);\n final ECPVaadinView ecpVaadinView = ECPVaadinViewRenderer.INSTANCE.render(USER);\n setContent(ecpVaadinView.getComponent());\n }\n @Override\n protected void refresh(VaadinRequest request) {\n }\n}"}}},{"rowIdx":1283,"cells":{"answer":{"kind":"string","value":"package org.openhab.binding.heos.internal.discovery;\nimport static org.openhab.binding.heos.HeosBindingConstants.*;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport org.eclipse.jdt.annotation.NonNullByDefault;\nimport org.eclipse.jdt.annotation.Nullable;\nimport org.eclipse.smarthome.config.discovery.DiscoveryResult;\nimport org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder;\nimport org.eclipse.smarthome.config.discovery.upnp.UpnpDiscoveryParticipant;\nimport org.eclipse.smarthome.core.thing.ThingTypeUID;\nimport org.eclipse.smarthome.core.thing.ThingUID;\nimport org.jupnp.model.meta.DeviceDetails;\nimport org.jupnp.model.meta.ManufacturerDetails;\nimport org.jupnp.model.meta.ModelDetails;\nimport org.jupnp.model.meta.RemoteDevice;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n/**\n * The {@link HeosDiscoveryParticipant} discovers the HEOS Player of the\n * network via an UPnP interface.\n *\n * @author Johannes Einig - Initial contribution\n */\n@NonNullByDefault\npublic class HeosDiscoveryParticipant implements UpnpDiscoveryParticipant {\n private Logger logger = LoggerFactory.getLogger(HeosDiscoveryParticipant.class);\n @Override\n public Set<ThingTypeUID> getSupportedThingTypeUIDs() {\n return Collections.singleton(THING_TYPE_BRIDGE);\n }\n @Override\n public @Nullable DiscoveryResult createResult(RemoteDevice device) {\n ThingUID uid = getThingUID(device);\n if (uid != null) {\n Map<String, Object> properties = new HashMap<>(2);\n properties.put(HOST, device.getIdentity().getDescriptorURL().getHost());\n properties.put(NAME, device.getDetails().getModelDetails().getModelName());\n DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties)\n .withLabel(device.getDetails().getFriendlyName()).withRepresentationProperty(PLAYER_TYPE).build();\n logger.info(\"Found HEOS device with UID: {}\", uid.getAsString());\n return result;\n }\n return null;\n }\n @Override\n public @Nullable ThingUID getThingUID(RemoteDevice device) {\n Optional<RemoteDevice> optDevice = Optional.ofNullable(device);\n String modelName = optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getModelDetails)\n .map(ModelDetails::getModelName).orElse(\"UNKNOWN\");\n String modelManufacturer = optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getManufacturerDetails)\n .map(ManufacturerDetails::getManufacturer).orElse(\"UNKNOWN\");\n if (modelManufacturer.equals(\"Denon\")) {\n if (modelName.startsWith(\"HEOS\") || modelName.endsWith(\"H\")) {\n if (device.getType().getType().startsWith(\"ACT\")) {\n return new ThingUID(THING_TYPE_BRIDGE,\n optDevice.get().getIdentity().getUdn().getIdentifierString());\n }\n }\n }\n return null;\n // optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getModelDetails).map(ModelDetails::getModelName)\n // .ifPresent(modelName -> {\n // optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getManufacturerDetails)\n // .map(ManufacturerDetails::getManufacturer).ifPresent(modelManufacturer -> {\n // if (modelManufacturer.equals(\"Denon\")) {\n // if (modelName.startsWith(\"HEOS\") || modelName.endsWith(\"H\")) {\n // if (device.getType().getType().startsWith(\"ACT\")) {\n // thingUID = new ThingUID(THING_TYPE_BRIDGE,\n // optDevice.get().getIdentity().getUdn().getIdentifierString());\n // return thingUID;\n // DeviceDetails details = device.getDetails();\n // if (details != null) {\n // ModelDetails modelDetails = details.getModelDetails();\n // ManufacturerDetails modelManufacturerDetails = details.getManufacturerDetails();\n // if (modelDetails != null && modelManufacturerDetails != null) {\n // String modelName = modelDetails.getModelName();\n // String modelManufacturer = modelManufacturerDetails.getManufacturer();\n // if (modelName != null && modelManufacturer != null) {\n // if (modelManufacturer.equals(\"Denon\")) {\n // if (modelName.startsWith(\"HEOS\") || modelName.endsWith(\"H\")) {\n // if (device.getType().getType().startsWith(\"ACT\")) {\n // return new ThingUID(THING_TYPE_BRIDGE,\n // device.getIdentity().getUdn().getIdentifierString());\n // return null;\n }\n}"}}},{"rowIdx":1284,"cells":{"answer":{"kind":"string","value":"package org.eclipse.persistence.exceptions.i18n;\nimport java.text.MessageFormat;\nimport java.util.Locale;\nimport java.util.ResourceBundle;\nimport java.util.Vector;\nimport org.eclipse.persistence.internal.helper.ConversionManager;\nimport org.eclipse.persistence.internal.helper.Helper;\npublic class ExceptionMessageGenerator {\n /**\n * Return the loader for loading the resource bundles.\n */\n public static ClassLoader getLoader() {\n ClassLoader loader = ExceptionMessageGenerator.class.getClassLoader();\n if (loader == null) {\n loader = ConversionManager.getDefaultManager().getLoader();\n }\n return loader;\n }\n /**\n * Return the message for the given exception class and error number.\n */\n public static String buildMessage(Class exceptionClass, int errorNumber, Object[] arguments) {\n final String CR = System.getProperty(\"line.separator\");\n String shortClassName = Helper.getShortClassName(exceptionClass);\n String message = \"\";\n ResourceBundle bundle = null;\n // JDK 1.1 MessageFormat can't handle null arguments\n for (int i = 0; i < arguments.length; i++) {\n if (arguments[i] == null) {\n arguments[i] = \"null\";\n }\n }\n bundle = ResourceBundle.getBundle(\"org.eclipse.persistence.exceptions.i18n.\" + shortClassName + \"Resource\", Locale.getDefault(), getLoader());\n try {\n message = bundle.getString(String.valueOf(errorNumber));\n } catch (java.util.MissingResourceException mre) {\n // Found bundle, but couldn't find exception translation.\n // Get the current language's NoExceptionTranslationForThisLocale message.\n bundle = ResourceBundle.getBundle(\"org.eclipse.persistence.exceptions.i18n.ExceptionResource\", Locale.getDefault(), getLoader());\n String noTranslationMessage = bundle.getString(\"NoExceptionTranslationForThisLocale\");\n Object[] args = { CR };\n return format(message, arguments) + format(noTranslationMessage, args);\n }\n return format(message, arguments);\n }\n /**\n * Return the formatted message for the given exception class and error number.\n */\n //Bug#4619864 Catch any exception during formatting and try to throw that exception. One possibility is toString() to an argument\n protected static String format(String message, Object[] arguments) {\n try {\n return MessageFormat.format(message, arguments);\n } catch (Exception ex) {\n ResourceBundle bundle = null;\n bundle = ResourceBundle.getBundle(\"org.eclipse.persistence.exceptions.i18n.ExceptionResource\", Locale.getDefault(), getLoader());\n String errorMessage = bundle.getString(\"ErrorFormattingMessage\");\n Vector vec = new Vector();\n if (arguments != null) {\n for (int index = 0; index < arguments.length; index++) {\n try {\n vec.add(arguments[index].toString());\n } catch (Exception ex2) {\n vec.add(ex2);\n }\n }\n }\n return MessageFormat.format(errorMessage, new Object[] {message, vec});\n }\n }\n /**\n * Get one of the generic headers used for the exception's toString().\n *\n * E.g., \"EXCEPTION DESCRIPTION: \", \"ERROR CODE: \", etc.\n */\n public static String getHeader(String headerLabel) {\n ResourceBundle bundle = null;\n try {\n bundle = ResourceBundle.getBundle(\"org.eclipse.persistence.exceptions.i18n.ExceptionResource\", Locale.getDefault(), getLoader());\n return bundle.getString(headerLabel);\n } catch (java.util.MissingResourceException mre) {\n return \"[\" + headerLabel + \"]\";\n }\n }\n}"}}},{"rowIdx":1285,"cells":{"answer":{"kind":"string","value":"package org.eclipse.persistence.internal.oxm.record;\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.xml.namespace.QName;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.XMLStreamReader;\nimport org.eclipse.persistence.internal.oxm.record.namespaces.UnmarshalNamespaceContext;\nimport org.eclipse.persistence.oxm.XMLConstants;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.ContentHandler;\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXNotRecognizedException;\nimport org.xml.sax.SAXNotSupportedException;\nimport org.xml.sax.ext.LexicalHandler;\n/**\n * Convert and XMLStreamReader into SAX events.\n */\npublic class XMLStreamReaderReader extends XMLReader {\n private ContentHandler contentHandler;\n private LexicalHandler lexicalHandler;\n private ErrorHandler errorHandler;\n private int depth = 0;\n public XMLStreamReaderReader() {\n }\n @Override\n public ContentHandler getContentHandler() {\n return contentHandler;\n }\n @Override\n public void setContentHandler(ContentHandler aContentHandler) {\n this.contentHandler = aContentHandler;\n }\n @Override\n public ErrorHandler getErrorHandler() {\n return errorHandler;\n }\n @Override\n public void setErrorHandler(ErrorHandler anErrorHandler) {\n this.errorHandler = anErrorHandler;\n }\n @Override\n public void setProperty (String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {\n if(name.equals(\"http://xml.org/sax/properties/lexical-handler\")) {\n lexicalHandler = (LexicalHandler)value;\n }\n }\n @Override\n public void parse(InputSource input) throws SAXException {\n if(input instanceof XMLStreamReaderInputSource) {\n XMLStreamReader xmlStreamReader = ((XMLStreamReaderInputSource) input).getXmlStreamReader();\n parse(xmlStreamReader);\n }\n }\n @Override\n public void parse(InputSource input, SAXUnmarshallerHandler saxUnmarshallerHandler) throws SAXException {\n if(input instanceof XMLStreamReaderInputSource) {\n XMLStreamReader xmlStreamReader = ((XMLStreamReaderInputSource) input).getXmlStreamReader();\n saxUnmarshallerHandler.setUnmarshalNamespaceResolver(new UnmarshalNamespaceContext(xmlStreamReader));\n parse(xmlStreamReader);\n }\n }\n public void parse(String systemId) throws SAXException {}\n private void parse(XMLStreamReader xmlStreamReader) throws SAXException {\n try{\n parseEvent(xmlStreamReader);\n while(depth > 0 && xmlStreamReader.hasNext()) {\n xmlStreamReader.next();\n parseEvent(xmlStreamReader);\n }\n }catch(XMLStreamException e) {\n throw new RuntimeException(e);\n }\n }\n private void parseEvent(XMLStreamReader xmlStreamReader) throws SAXException {\n if(null == getContentHandler()) {\n return;\n }\n switch (xmlStreamReader.getEventType()) {\n case XMLStreamReader.ATTRIBUTE: {\n break;\n }\n case XMLStreamReader.CDATA: {\n if(null == lexicalHandler) {\n getContentHandler().characters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());\n } else {\n lexicalHandler.startCDATA();\n getContentHandler().characters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());\n lexicalHandler.endCDATA();\n }\n break;\n }\n case XMLStreamReader.CHARACTERS: {\n getContentHandler().characters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());\n break;\n }\n case XMLStreamReader.COMMENT: {\n if(null != lexicalHandler) {\n lexicalHandler.comment(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());\n }\n break;\n }\n case XMLStreamReader.DTD: {\n break;\n }\n case XMLStreamReader.END_DOCUMENT: {\n depth\n getContentHandler().endDocument();\n return;\n }\n case XMLStreamReader.END_ELEMENT: {\n depth\n String prefix = xmlStreamReader.getPrefix();\n if(null == prefix || prefix.length() == 0) {\n getContentHandler().endElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), xmlStreamReader.getLocalName());\n } else {\n getContentHandler().endElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), prefix + XMLConstants.COLON + xmlStreamReader.getLocalName());\n }\n break;\n }\n case XMLStreamReader.ENTITY_DECLARATION: {\n break;\n }\n case XMLStreamReader.ENTITY_REFERENCE: {\n break;\n }\n case XMLStreamReader.NAMESPACE: {\n break;\n }\n case XMLStreamReader.NOTATION_DECLARATION: {\n break;\n }\n case XMLStreamReader.PROCESSING_INSTRUCTION: {\n getContentHandler().processingInstruction(xmlStreamReader.getPITarget(), xmlStreamReader.getPIData());\n break;\n }\n case XMLStreamReader.SPACE: {\n char[] characters = xmlStreamReader.getTextCharacters();\n getContentHandler().characters(characters, 0, characters.length);\n break;\n }\n case XMLStreamReader.START_DOCUMENT: {\n depth++;\n getContentHandler().startDocument();\n break;\n }\n case XMLStreamReader.START_ELEMENT: {\n depth++;\n String prefix = xmlStreamReader.getPrefix();\n if(null == prefix || prefix.length() == 0) {\n getContentHandler().startElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), xmlStreamReader.getLocalName(), new IndexedAttributeList(xmlStreamReader));\n } else {\n getContentHandler().startElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), prefix + XMLConstants.COLON + xmlStreamReader.getLocalName(), new IndexedAttributeList(xmlStreamReader));\n }\n break;\n }\n }\n }\n private static class IndexedAttributeList implements Attributes {\n private List<Attribute> attributes;\n public IndexedAttributeList(XMLStreamReader xmlStreamReader) {\n int namespaceCount = xmlStreamReader.getNamespaceCount();\n int attributeCount = xmlStreamReader.getAttributeCount();\n attributes = new ArrayList<Attribute>(attributeCount + namespaceCount);\n for(int x=0; x<namespaceCount; x++) {\n String uri = XMLConstants.XMLNS_URL;\n String localName = xmlStreamReader.getNamespacePrefix(x);\n String qName;\n if(null == localName || localName.length() == 0) {\n localName = XMLConstants.XMLNS;\n qName = XMLConstants.XMLNS;\n } else {\n qName = XMLConstants.XMLNS + XMLConstants.COLON + localName;\n }\n String value = xmlStreamReader.getNamespaceURI(x);\n attributes.add(new Attribute(uri, localName, qName, value));\n }\n for(int x=0; x<attributeCount; x++) {\n String uri = xmlStreamReader.getAttributeNamespace(x);\n String localName = xmlStreamReader.getAttributeLocalName(x);\n String prefix = xmlStreamReader.getAttributePrefix(x);\n String qName;\n if(null == prefix || prefix.length() == 0) {\n qName = localName;\n } else {\n qName = prefix + XMLConstants.COLON + localName;\n }\n String value = xmlStreamReader.getAttributeValue(x);\n attributes.add(new Attribute(uri, localName, qName, value));\n }\n }\n public int getIndex(String qName) {\n if(null == qName) {\n return -1;\n }\n int index = 0;\n for(Attribute attribute : attributes) {\n if(qName.equals(attribute.getName())) {\n return index;\n }\n index++;\n }\n return -1;\n }\n public int getIndex(String uri, String localName) {\n if(null == localName) {\n return -1;\n }\n int index = 0;\n for(Attribute attribute : attributes) {\n QName testQName = new QName(uri, localName);\n if(attribute.getQName().equals(testQName)) {\n return index;\n }\n index++;\n }\n return -1;\n }\n public int getLength() {\n return attributes.size();\n }\n public String getLocalName(int index) {\n return attributes.get(index).getQName().getLocalPart();\n }\n public String getQName(int index) {\n return attributes.get(index).getName();\n }\n public String getType(int index) {\n return XMLConstants.CDATA;\n }\n public String getType(String name) {\n return XMLConstants.CDATA;\n }\n public String getType(String uri, String localName) {\n return XMLConstants.CDATA;\n }\n public String getURI(int index) {\n return attributes.get(index).getQName().getNamespaceURI();\n }\n public String getValue(int index) {\n return attributes.get(index).getValue();\n }\n public String getValue(String qName) {\n int index = getIndex(qName);\n if(-1 == index) {\n return null;\n }\n return attributes.get(index).getValue();\n }\n public String getValue(String uri, String localName) {\n int index = getIndex(uri, localName);\n if(-1 == index) {\n return null;\n }\n return attributes.get(index).getValue();\n }\n }\n private static class Attribute {\n private QName qName;\n private String name;\n private String value;\n public Attribute(String uri, String localName, String name, String value) {\n this.qName = new QName(uri, localName);\n this.name = name;\n this.value = value;\n }\n public QName getQName() {\n return qName;\n }\n public String getName() {\n return name;\n }\n public String getValue() {\n return value;\n }\n }\n}"}}},{"rowIdx":1286,"cells":{"answer":{"kind":"string","value":"package net.java.sip.communicator.impl.protocol.yahoo;\nimport java.io.*;\nimport net.java.sip.communicator.service.protocol.*;\nimport net.java.sip.communicator.service.protocol.event.*;\nimport net.java.sip.communicator.util.*;\nimport ymsg.network.*;\nimport ymsg.network.event.*;\n/**\n * An implementation of the protocol provider service over the Yahoo protocol\n *\n * @author Damian Minkov\n */\npublic class ProtocolProviderServiceYahooImpl\n extends AbstractProtocolProviderService\n{\n private static final Logger logger =\n Logger.getLogger(ProtocolProviderServiceYahooImpl.class);\n private YahooSession yahooSession = null;\n /**\n * indicates whether or not the provider is initialized and ready for use.\n */\n private boolean isInitialized = false;\n /**\n * We use this to lock access to initialization.\n */\n private final Object initializationLock = new Object();\n /**\n * The identifier of the account that this provider represents.\n */\n private AccountID accountID = null;\n /**\n * Used when we need to re-register\n */\n private SecurityAuthority authority = null;\n private OperationSetPersistentPresenceYahooImpl persistentPresence = null;\n private OperationSetTypingNotificationsYahooImpl typingNotifications = null;\n /**\n * The logo corresponding to the msn protocol.\n */\n private ProtocolIconYahooImpl yahooIcon\n = new ProtocolIconYahooImpl();\n /**\n * Returns the state of the registration of this protocol provider\n * @return the <tt>RegistrationState</tt> that this provider is\n * currently in or null in case it is in a unknown state.\n */\n public RegistrationState getRegistrationState()\n {\n if(yahooSession != null &&\n yahooSession.getSessionStatus() == StatusConstants.MESSAGING)\n return RegistrationState.REGISTERED;\n else\n return RegistrationState.UNREGISTERED;\n }\n /**\n * Starts the registration process. Connection details such as\n * registration server, user name/number are provided through the\n * configuration service through implementation specific properties.\n *\n * @param authority the security authority that will be used for resolving\n * any security challenges that may be returned during the\n * registration or at any moment while wer're registered.\n * @throws OperationFailedException with the corresponding code it the\n * registration fails for some reason (e.g. a networking error or an\n * implementation problem).\n */\n public void register(final SecurityAuthority authority)\n throws OperationFailedException\n {\n if(authority == null)\n throw new IllegalArgumentException(\n \"The register method needs a valid non-null authority impl \"\n + \" in order to be able and retrieve passwords.\");\n this.authority = authority;\n connectAndLogin(authority, SecurityAuthority.AUTHENTICATION_REQUIRED);\n }\n /**\n * Connects and logins to the server\n * @param authority SecurityAuthority\n * @param authReasonCode the authentication reason code, which should\n * indicate why are making an authentication request\n * @throws XMPPException if we cannot connect to the server - network problem\n * @throws OperationFailedException if login parameters\n * as server port are not correct\n */\n private void connectAndLogin( SecurityAuthority authority,\n int authReasonCode)\n throws OperationFailedException\n {\n synchronized(initializationLock)\n {\n //verify whether a password has already been stored for this account\n String password = YahooActivator.\n getProtocolProviderFactory().loadPassword(getAccountID());\n //decode\n if (password == null)\n {\n //create a default credentials object\n UserCredentials credentials = new UserCredentials();\n credentials.setUserName(getAccountID().getUserID());\n //request a password from the user\n credentials = authority.obtainCredentials(\n ProtocolNames.YAHOO,\n credentials,\n authReasonCode);\n //extract the password the user passed us.\n char[] pass = credentials.getPassword();\n // the user didn't provide us a password (canceled the operation)\n if(pass == null)\n {\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.UNREGISTERED,\n RegistrationStateChangeEvent.REASON_USER_REQUEST, \"\");\n return;\n }\n password = new String(pass);\n if (credentials.isPasswordPersistent())\n {\n YahooActivator.getProtocolProviderFactory()\n .storePassword(getAccountID(), password);\n }\n }\n yahooSession = new YahooSession();\n yahooSession.addSessionListener(new YahooConnectionListener());\n try\n {\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.REGISTERING,\n RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);\n yahooSession.login(getAccountID().getUserID(), password);\n if(yahooSession.getSessionStatus()==StatusConstants.MESSAGING)\n {\n persistentPresence.fireProviderStatusChangeEvent(\n persistentPresence.getPresenceStatus(),\n persistentPresence.yahooStatusToPresenceStatus(\n yahooSession.getStatus()));\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.REGISTERED,\n RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);\n }\n else\n {\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.UNREGISTERED,\n RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);\n }\n }\n catch (LoginRefusedException ex)\n {\n if(ex.getStatus() == StatusConstants.STATUS_BADUSERNAME)\n {\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.AUTHENTICATION_FAILED,\n RegistrationStateChangeEvent.REASON_NON_EXISTING_USER_ID,\n null);\n reregister(SecurityAuthority.WRONG_USERNAME);\n }\n else if(ex.getStatus() == StatusConstants.STATUS_BAD)\n {\n YahooActivator.getProtocolProviderFactory()\n .storePassword(getAccountID(), null);\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.AUTHENTICATION_FAILED,\n RegistrationStateChangeEvent.REASON_AUTHENTICATION_FAILED,\n null);\n // Try to re-register and ask the user to retype the password.\n reregister(SecurityAuthority.WRONG_PASSWORD);\n }\n else if(ex.getStatus() == StatusConstants.STATUS_LOCKED)\n {\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.AUTHENTICATION_FAILED,\n RegistrationStateChangeEvent.REASON_RECONNECTION_RATE_LIMIT_EXCEEDED,\n null);\n }\n }\n catch (IOException ex)\n {\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.CONNECTION_FAILED,\n RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);\n }\n }\n }\n /**\n * Reconnects if fails fire connection failed.\n * @param reasonCode the appropriate <tt>SecurityAuthority</tt> reasonCode,\n * which would specify the reason for which we're re-calling the login.\n */\n void reregister(int reasonCode)\n {\n try\n {\n connectAndLogin(authority, reasonCode);\n }\n catch (OperationFailedException ex)\n {\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.CONNECTION_FAILED,\n RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);\n }\n }\n /**\n * Ends the registration of this protocol provider with the service.\n */\n public void unregister()\n {\n unregister(true);\n }\n /**\n * Unregister and fire the event if requested\n * @param fireEvent boolean\n */\n void unregister(boolean fireEvent)\n {\n RegistrationState currRegState = getRegistrationState();\n try\n {\n if((yahooSession != null)\n && (yahooSession.getSessionStatus() == StatusConstants.MESSAGING))\n yahooSession.logout();\n }\n catch(Exception ex)\n {\n logger.error(\"Cannot logout! \", ex);\n }\n yahooSession = null;\n if(fireEvent)\n fireRegistrationStateChanged(\n currRegState,\n RegistrationState.UNREGISTERED,\n RegistrationStateChangeEvent.REASON_USER_REQUEST,\n null);\n }\n /**\n * Returns the short name of the protocol that the implementation of this\n * provider is based upon (like SIP, Msn, ICQ/AIM, or others for\n * example).\n *\n * @return a String containing the short name of the protocol this\n * service is taking care of.\n */\n public String getProtocolName()\n {\n return ProtocolNames.YAHOO;\n }\n /**\n * Initialized the service implementation, and puts it in a sate where it\n * could interoperate with other services. It is strongly recomended that\n * properties in this Map be mapped to property names as specified by\n * <tt>AccountProperties</tt>.\n *\n * @param screenname the account id/uin/screenname of the account that\n * we're about to create\n * @param accountID the identifier of the account that this protocol\n * provider represents.\n *\n * @see net.java.sip.communicator.service.protocol.AccountID\n */\n protected void initialize(String screenname,\n AccountID accountID)\n {\n synchronized(initializationLock)\n {\n this.accountID = accountID;\n addSupportedOperationSet(\n OperationSetInstantMessageTransform.class,\n new OperationSetInstantMessageTransformImpl());\n //initialize the presence operationset\n persistentPresence\n = new OperationSetPersistentPresenceYahooImpl(this);\n addSupportedOperationSet(\n OperationSetPersistentPresence.class,\n persistentPresence);\n //register it once again for those that simply need presence\n addSupportedOperationSet(\n OperationSetPresence.class,\n persistentPresence);\n //initialize the IM operation set\n addSupportedOperationSet(\n OperationSetBasicInstantMessaging.class,\n new OperationSetBasicInstantMessagingYahooImpl(this));\n //initialize the multi user chat operation set\n addSupportedOperationSet(\n OperationSetAdHocMultiUserChat.class,\n new OperationSetAdHocMultiUserChatYahooImpl(this));\n //initialize the typing notifications operation set\n typingNotifications\n = new OperationSetTypingNotificationsYahooImpl(this);\n addSupportedOperationSet(\n OperationSetTypingNotifications.class,\n typingNotifications);\n addSupportedOperationSet(\n OperationSetFileTransfer.class,\n new OperationSetFileTransferYahooImpl(this));\n isInitialized = true;\n }\n }\n /**\n * Makes the service implementation close all open sockets and release\n * any resources that it might have taken and prepare for\n * shutdown/garbage collection.\n */\n public void shutdown()\n {\n synchronized(initializationLock){\n unregister(false);\n yahooSession = null;\n isInitialized = false;\n }\n }\n /**\n * Returns true if the provider service implementation is initialized and\n * ready for use by other services, and false otherwise.\n *\n * @return true if the provider is initialized and ready for use and false\n * otherwise\n */\n public boolean isInitialized()\n {\n return isInitialized;\n }\n /**\n * Returns the AccountID that uniquely identifies the account represented\n * by this instance of the ProtocolProviderService.\n * @return the id of the account represented by this provider.\n */\n public AccountID getAccountID()\n {\n return accountID;\n }\n /**\n * Returns the Yahoo<tt>Session</tt>opened by this provider\n * @return a reference to the <tt>Session</tt> last opened by this\n * provider.\n */\n YahooSession getYahooSession()\n {\n return yahooSession;\n }\n /**\n * Creates a RegistrationStateChange event corresponding to the specified\n * old and new states and notifies all currently registered listeners.\n *\n * @param oldState the state that the provider had before the change\n * occurred\n * @param newState the state that the provider is currently in.\n * @param reasonCode a value corresponding to one of the REASON_XXX fields\n * of the RegistrationStateChangeEvent class, indicating the reason for\n * this state transition.\n * @param reason a String further explaining the reason code or null if\n * no such explanation is necessary.\n */\n public void fireRegistrationStateChanged( RegistrationState oldState,\n RegistrationState newState,\n int reasonCode,\n String reason)\n {\n if(newState.equals(RegistrationState.UNREGISTERED) ||\n newState.equals(RegistrationState.CONNECTION_FAILED))\n {\n unregister(false);\n yahooSession = null;\n }\n super.fireRegistrationStateChanged(oldState, newState, reasonCode, reason);\n }\n /**\n * Listens when we are logged in the server\n * or incoming exception in the lib impl.\n */\n private class YahooConnectionListener\n extends SessionAdapter\n {\n /**\n * Yahoo has logged us off the system, or the connection was lost\n **/\n public void connectionClosed(SessionEvent ev)\n {\n unregister(true);\n if(isRegistered())\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.CONNECTION_FAILED,\n RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);\n }\n public void inputExceptionThrown(SessionExceptionEvent ev)\n {\n if(ev.getException() instanceof YMSG9BadFormatException)\n {\n logger.error(\"Yahoo protocol exception occured exception\",\n ev.getException());\n logger.error(\"Yahoo protocol exception occured exception cause\",\n ev.getException().getCause());\n }\n else\n logger.error(\n \"Yahoo protocol exception occured\", ev.getException());\n unregister(false);\n if(isRegistered())\n fireRegistrationStateChanged(\n getRegistrationState(),\n RegistrationState.UNREGISTERED,\n RegistrationStateChangeEvent.REASON_INTERNAL_ERROR, null);\n }\n }\n /**\n * Returns the yahoo protocol icon.\n * @return the yahoo protocol icon\n */\n public ProtocolIcon getProtocolIcon()\n {\n return yahooIcon;\n }\n}"}}},{"rowIdx":1287,"cells":{"answer":{"kind":"string","value":"package gobblin.ingestion.google.adwords;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.LinkedBlockingDeque;\nimport java.util.zip.GZIPInputStream;\nimport org.apache.commons.lang3.tuple.Pair;\nimport org.joda.time.DateTime;\nimport org.joda.time.format.DateTimeFormat;\nimport org.joda.time.format.DateTimeFormatter;\nimport com.google.api.ads.adwords.lib.client.AdWordsSession;\nimport com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration;\nimport com.google.api.ads.adwords.lib.jaxb.v201609.DateRange;\nimport com.google.api.ads.adwords.lib.jaxb.v201609.DownloadFormat;\nimport com.google.api.ads.adwords.lib.jaxb.v201609.ReportDefinition;\nimport com.google.api.ads.adwords.lib.jaxb.v201609.ReportDefinitionDateRangeType;\nimport com.google.api.ads.adwords.lib.jaxb.v201609.ReportDefinitionReportType;\nimport com.google.api.ads.adwords.lib.jaxb.v201609.Selector;\nimport com.google.api.ads.adwords.lib.utils.ReportDownloadResponse;\nimport com.google.api.ads.adwords.lib.utils.ReportDownloadResponseException;\nimport com.google.api.ads.adwords.lib.utils.ReportException;\nimport com.google.api.ads.adwords.lib.utils.v201609.ReportDownloader;\nimport com.google.api.ads.common.lib.exception.ValidationException;\nimport com.google.api.client.util.BackOff;\nimport com.google.api.client.util.ExponentialBackOff;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonParser;\nimport com.opencsv.CSVParser;\nimport lombok.extern.slf4j.Slf4j;\nimport gobblin.configuration.WorkUnitState;\nimport gobblin.source.extractor.extract.LongWatermark;\n@Slf4j\npublic class GoogleAdWordsReportDownloader {\n private final static CSVParser splitter = new CSVParser(',', '\"', '\\\\');\n private final static int SIZE = 4096; //Buffer size for unzipping stream.\n private final boolean _skipReportHeader;\n private final boolean _skipColumnHeader;\n private final boolean _skipReportSummary;\n private final boolean _includeZeroImpressions;\n private final boolean _useRawEnumValues;\n private final AdWordsSession _rootSession;\n private final ExponentialBackOff.Builder backOffBuilder =\n new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(1000 * 60 * 5);\n private final List<String> _columnNames;\n private final ReportDefinitionReportType _reportType;\n private final ReportDefinitionDateRangeType _dateRangeType;\n private final String _startDate;\n private final String _endDate;\n private final boolean _dailyPartition;\n private final static DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(\"yyyyMMdd\");\n private final static DateTimeFormatter watermarkFormatter = DateTimeFormat.forPattern(\"yyyyMMddHHmmss\");\n /**\n * debug in FILE mode is to download reports in file format directly\n */\n private final String _debugFileOutputPath;\n /**\n * debug in STRING mode is to download reports in strings, then concate and convert all strings to files.\n */\n private final String _debugStringOutputPath;\n public GoogleAdWordsReportDownloader(AdWordsSession rootSession, WorkUnitState state,\n ReportDefinitionReportType reportType, ReportDefinitionDateRangeType dateRangeType, String schema) {\n _rootSession = rootSession;\n _reportType = reportType;\n _dateRangeType = dateRangeType;\n _columnNames = schemaToColumnNames(schema);\n log.info(\"Downloaded fields are: \" + Arrays.toString(_columnNames.toArray()));\n long lowWatermark = state.getWorkunit().getLowWatermark(LongWatermark.class).getValue();\n _startDate = dateFormatter.print(watermarkFormatter.parseDateTime(Long.toString(lowWatermark)));\n _endDate = _startDate;\n _dailyPartition = state.getPropAsBoolean(GoogleAdWordsSource.KEY_CUSTOM_DATE_DAILY, false);\n _debugFileOutputPath = state.getProp(GoogleAdWordsSource.KEY_DEBUG_PATH_FILE, \"\");\n _debugStringOutputPath = state.getProp(GoogleAdWordsSource.KEY_DEBUG_PATH_STRING, \"\");\n _skipReportHeader = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_SKIP_REPORT_HEADER, true);\n _skipColumnHeader = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_SKIP_COLUMN_HEADER, true);\n _skipReportSummary = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_SKIP_REPORT_SUMMARY, true);\n _useRawEnumValues = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_USE_RAW_ENUM_VALUES, false);\n _includeZeroImpressions = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_INCLUDE_ZERO_IMPRESSION, false);\n }\n static List<String> schemaToColumnNames(String schemaString) {\n JsonArray schemaArray = new JsonParser().parse(schemaString).getAsJsonArray();\n List<String> fields = new ArrayList<>();\n for (int i = 0; i < schemaArray.size(); i++) {\n fields.add(schemaArray.get(i).getAsJsonObject().get(\"columnName\").getAsString());\n }\n return fields;\n }\n public void downloadAllReports(Collection<String> accounts, final LinkedBlockingDeque<String[]> reportRows)\n throws InterruptedException {\n ExecutorService threadPool = Executors.newFixedThreadPool(Math.min(8, accounts.size()));\n List<Pair<String, String>> dates = getDates();\n Map<String, Future<Void>> jobs = new HashMap<>();\n for (String acc : accounts) {\n final String account = acc;\n for (Pair<String, String> dateRange : dates) {\n final Pair<String, String> range = dateRange;\n final String jobName;\n if (_dateRangeType.equals(ReportDefinitionDateRangeType.ALL_TIME)) {\n jobName = String.format(\"'all-time report for %s'\", account);\n } else {\n jobName = String.format(\"'report for %s from %s to %s'\", account, range.getLeft(), range.getRight());\n }\n Future<Void> job = threadPool.submit(new Callable<Void>() {\n @Override\n public Void call()\n throws ReportDownloadResponseException, InterruptedException, IOException, ReportException {\n log.info(\"Start downloading \" + jobName);\n ExponentialBackOff backOff = backOffBuilder.build();\n int numberOfAttempts = 0;\n while (true) {\n ++numberOfAttempts;\n try {\n downloadReport(account, range.getLeft(), range.getRight(), reportRows);\n log.info(\"Successfully downloaded \" + jobName);\n return null;\n } catch (ReportException e) {\n long sleepMillis = backOff.nextBackOffMillis();\n log.info(\"Downloading %s failed #%d try: %s. Will sleep for %d milliseconds.\", jobName,\n numberOfAttempts, e.getMessage(), sleepMillis);\n if (sleepMillis == BackOff.STOP) {\n throw new ReportException(String\n .format(\"Downloading %s failed after maximum elapsed millis: %d\", jobName,\n backOff.getMaxElapsedTimeMillis()), e);\n }\n Thread.sleep(sleepMillis);\n }\n }\n }\n });\n jobs.put(jobName, job);\n Thread.sleep(100);\n }\n }\n threadPool.shutdown();\n //Collect all failed jobs.\n Map<String, Exception> failedJobs = new HashMap<>();\n for (Map.Entry<String, Future<Void>> job : jobs.entrySet()) {\n try {\n job.getValue().get();\n } catch (Exception e) {\n failedJobs.put(job.getKey(), e);\n }\n }\n if (!failedJobs.isEmpty()) {\n log.error(String.format(\"%d downloading jobs failed: \", failedJobs.size()));\n for (Map.Entry<String, Exception> fail : failedJobs.entrySet()) {\n log.error(String.format(\"%s => %s\", fail.getKey(), fail.getValue().getMessage()));\n }\n }\n log.info(\"End of downloading all reports.\");\n }\n /**\n * @param account the account of the report you want to download\n * @param startDate start date for custom_date range type\n * @param endDate end date for custom_date range type\n * @param reportRows the sink that accumulates all downloaded rows\n * @throws ReportDownloadResponseException This is not retryable\n * @throws ReportException ReportException represents a potentially retryable error\n */\n private void downloadReport(String account, String startDate, String endDate,\n LinkedBlockingDeque<String[]> reportRows)\n throws ReportDownloadResponseException, ReportException, InterruptedException, IOException {\n Selector selector = new Selector();\n selector.getFields().addAll(_columnNames);\n String reportName;\n if (_dateRangeType.equals(ReportDefinitionDateRangeType.CUSTOM_DATE)) {\n DateRange value = new DateRange();\n value.setMin(startDate);\n value.setMax(endDate);\n selector.setDateRange(value);\n reportName = String.format(\"%s_%s/%s_%s.csv\", startDate, endDate, _reportType.toString(), account);\n } else {\n reportName = String.format(\"all_time/%s_%s.csv\", _reportType.toString(), account);\n }\n ReportDefinition reportDef = new ReportDefinition();\n reportDef.setReportName(reportName);\n reportDef.setDateRangeType(_dateRangeType);\n reportDef.setReportType(_reportType);\n reportDef.setDownloadFormat(DownloadFormat.GZIPPED_CSV);\n reportDef.setSelector(selector);\n //API defaults all configurations to false\n ReportingConfiguration reportConfig =\n new ReportingConfiguration.Builder().skipReportHeader(_skipReportHeader).skipColumnHeader(_skipColumnHeader)\n .skipReportSummary(_skipReportSummary)\n .useRawEnumValues(_useRawEnumValues) //return enum field values as enum values instead of display values\n .includeZeroImpressions(_includeZeroImpressions).build();\n AdWordsSession.ImmutableAdWordsSession session;\n try {\n session = _rootSession.newBuilder().withClientCustomerId(account).withReportingConfiguration(reportConfig)\n .buildImmutable();\n } catch (ValidationException e) {\n throw new RuntimeException(e);\n }\n ReportDownloader downloader = new ReportDownloader(session);\n ReportDownloadResponse response = downloader.downloadReport(reportDef);\n InputStream zippedStream = response.getInputStream();\n if (zippedStream == null) {\n log.warn(\"Got empty stream for \" + reportName);\n return;\n }\n if (!_debugFileOutputPath.trim().isEmpty()) {\n //FILE mode debug will not save output to GOBBLIN_WORK_DIR\n File debugFile = new File(_debugFileOutputPath, reportName);\n createPath(debugFile);\n writeZippedStreamToFile(zippedStream, debugFile);\n return;\n }\n FileWriter debugFileWriter = null;\n try {\n if (!_debugStringOutputPath.trim().isEmpty()) {\n //if STRING mode debug is enabled. A copy of downloaded strings/reports will be saved.\n File debugFile = new File(_debugStringOutputPath, reportName);\n createPath(debugFile);\n debugFileWriter = new FileWriter(debugFile);\n }\n processResponse(zippedStream, reportRows, debugFileWriter);\n } catch (IOException e) {\n throw new RuntimeException(\n String.format(\"Failed unzipping and processing records for %s. Reason is: %s\", reportName, e.getMessage()),\n e);\n } finally {\n if (debugFileWriter != null) {\n debugFileWriter.close();\n }\n }\n }\n private static void createPath(File file) {\n //Clean up file if exists\n if (file.exists()) {\n boolean delete = file.delete();\n if (!delete) {\n throw new RuntimeException(String.format(\"Cannot delete debug file: %s\", file));\n }\n }\n boolean created = new File(file.getParent()).mkdirs();\n if (!created) {\n throw new RuntimeException(String.format(\"Cannot create debug file: %s\", file));\n }\n }\n private static GZIPInputStream processResponse(InputStream zippedStream, LinkedBlockingDeque<String[]> reportRows,\n FileWriter debugFw)\n throws IOException, InterruptedException {\n byte[] buffer = new byte[SIZE];\n try (GZIPInputStream gzipInputStream = new GZIPInputStream(zippedStream)) {\n String partiallyConsumed = \"\";\n while (true) {\n int c = gzipInputStream.read(buffer, 0, SIZE);\n if (c == -1) {\n break; //end of stream\n }\n if (c == 0) {\n continue; //read empty, continue reading\n }\n String str = new String(buffer, 0, c, \"UTF-8\"); //\"c\" can very likely be less than SIZE.\n if (debugFw != null) {\n debugFw.write(str); //save a copy if STRING mode debug is enabled\n }\n partiallyConsumed = addToQueue(reportRows, partiallyConsumed, str);\n }\n return gzipInputStream;\n }\n }\n /**\n * Concatenate previously partially consumed string with current read, then try to split the whole string.\n * A whole record will be added to reportRows(data sink).\n * The last partially consumed string, if exists, will be returned to be processed in next round.\n */\n static String addToQueue(LinkedBlockingDeque<String[]> reportRows, String previous, String current)\n throws InterruptedException, IOException {\n int start = -1;\n int i = -1;\n int len = current.length();\n while (++i < len) {\n if (current.charAt(i) != '\\n') {\n continue;\n }\n String row;\n if (start < 0) {\n row = previous + current.substring(0, i);\n } else {\n row = current.substring(start, i);\n }\n String[] splits = splitter.parseLine(row);\n String[] transformed = new String[splits.length];\n for (int s = 0; s < splits.length; ++s) {\n String trimmed = splits[s].trim();\n if (trimmed.equals(\"\n transformed[s] = null;\n } else {\n transformed[s] = trimmed;\n }\n }\n reportRows.put(transformed);\n start = i + 1;\n }\n if (start < 0) {\n return previous + current;\n }\n return current.substring(start);\n }\n private void writeZippedStreamToFile(InputStream zippedStream, File reportFile)\n throws IOException {\n byte[] buffer = new byte[SIZE];\n int c;\n try (GZIPInputStream gzipInputStream = new GZIPInputStream(zippedStream);\n OutputStream unzipped = new FileOutputStream(reportFile)) {\n while ((c = gzipInputStream.read(buffer, 0, SIZE)) >= 0) {\n unzipped.write(buffer, 0, c);\n }\n }\n }\n public List<Pair<String, String>> getDates() {\n if (_dateRangeType.equals(ReportDefinitionDateRangeType.ALL_TIME)) {\n return Arrays.asList(Pair.of(\"\", \"\"));\n } else {\n DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(\"yyyyMMdd\");\n if (_dailyPartition) {\n DateTime start = dateFormatter.parseDateTime(_startDate);\n DateTime end = dateFormatter.parseDateTime(_endDate);\n List<Pair<String, String>> ret = new ArrayList<>();\n while (start.compareTo(end) <= 0) {\n ret.add(Pair.of(dateFormatter.print(start), dateFormatter.print(start)));\n start = start.plusDays(1);\n }\n return ret;\n } else {\n return Arrays.asList(Pair.of(_startDate, _endDate));\n }\n }\n }\n}"}}},{"rowIdx":1288,"cells":{"answer":{"kind":"string","value":"package org.dbflute.erflute.editor.model.diagram_contents.element.node.table;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.dbflute.erflute.core.util.Format;\nimport org.dbflute.erflute.db.DBManager;\nimport org.dbflute.erflute.db.DBManagerFactory;\nimport org.dbflute.erflute.editor.model.ObjectModel;\nimport org.dbflute.erflute.editor.model.diagram_contents.element.connection.Relationship;\nimport org.dbflute.erflute.editor.model.diagram_contents.element.connection.WalkerConnection;\nimport org.dbflute.erflute.editor.model.diagram_contents.element.node.DiagramWalker;\nimport org.dbflute.erflute.editor.model.diagram_contents.element.node.Location;\nimport org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.ColumnHolder;\nimport org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.CopyColumn;\nimport org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.ERColumn;\nimport org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.NormalColumn;\nimport org.dbflute.erflute.editor.model.diagram_contents.element.node.table.properties.TableViewProperties;\nimport org.dbflute.erflute.editor.model.diagram_contents.not_element.dictionary.CopyWord;\nimport org.dbflute.erflute.editor.model.diagram_contents.not_element.dictionary.Dictionary;\nimport org.dbflute.erflute.editor.model.diagram_contents.not_element.dictionary.Word;\nimport org.dbflute.erflute.editor.model.diagram_contents.not_element.group.ColumnGroup;\npublic abstract class TableView extends DiagramWalker implements ObjectModel, ColumnHolder, Comparable<TableView> {\n // Definition\n private static final long serialVersionUID = 1L;\n public static final String PROPERTY_CHANGE_PHYSICAL_NAME = \"table_view_physicalName\";\n public static final String PROPERTY_CHANGE_LOGICAL_NAME = \"table_view_logicalName\";\n public static final String PROPERTY_CHANGE_COLUMNS = \"columns\";\n public static final int DEFAULT_WIDTH = 120;\n public static final int DEFAULT_HEIGHT = 75;\n public static final Comparator<TableView> PHYSICAL_NAME_COMPARATOR = new TableViewPhysicalNameComparator();\n public static final Comparator<TableView> LOGICAL_NAME_COMPARATOR = new TableViewLogicalNameComparator();\n // Attribute\n private String physicalName;\n private String logicalName;\n private String description;\n protected List<ERColumn> columns;\n protected TableViewProperties tableViewProperties;\n // Constructor\n public TableView() {\n this.columns = new ArrayList<>();\n }\n // Location\n @Override\n public void setLocation(Location location) {\n super.setLocation(location);\n if (this.getDiagram() != null) {\n for (final Relationship relationship : getOutgoingRelationshipList()) {\n relationship.setParentMove();\n }\n for (final Relationship relation : getIncomingRelationshipList()) {\n relation.setParentMove();\n }\n }\n }\n // Column\n public List<NormalColumn> getNormalColumns() {\n final List<NormalColumn> normalColumns = new ArrayList<>();\n for (final ERColumn column : columns) {\n if (column instanceof NormalColumn) {\n normalColumns.add((NormalColumn) column);\n }\n }\n return normalColumns;\n }\n public List<NormalColumn> getExpandedColumns() {\n final List<NormalColumn> expandedColumns = new ArrayList<>();\n for (final ERColumn column : this.getColumns()) {\n if (column instanceof NormalColumn) {\n final NormalColumn normalColumn = (NormalColumn) column;\n expandedColumns.add(normalColumn);\n } else if (column instanceof ColumnGroup) {\n final ColumnGroup groupColumn = (ColumnGroup) column;\n expandedColumns.addAll(groupColumn.getColumns());\n }\n }\n return expandedColumns;\n }\n public void setDirty() {\n this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null);\n }\n public void addColumn(ERColumn column) {\n this.getColumns().add(column);\n column.setColumnHolder(this);\n this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null);\n }\n public void addColumn(int index, ERColumn column) {\n this.getColumns().add(index, column);\n column.setColumnHolder(this);\n this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null);\n }\n public void removeColumn(ERColumn column) {\n this.columns.remove(column);\n this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null);\n }\n public NormalColumn findColumnByPhysicalName(String physicalName) {\n final List<NormalColumn> normalColumns = getNormalColumns();\n for (final NormalColumn normalColumn : normalColumns) {\n if (physicalName.equalsIgnoreCase(normalColumn.getPhysicalName())) {\n return normalColumn;\n }\n }\n return null;\n }\n // Copy\n public TableView copyTableViewData(TableView to) {\n to.setDiagram(getDiagram());\n to.setPhysicalName(getPhysicalName());\n to.setLogicalName(getLogicalName());\n to.setDescription(getDescription());\n final List<ERColumn> columns = new ArrayList<>();\n for (final ERColumn fromColumn : getColumns()) {\n if (fromColumn instanceof NormalColumn) {\n final NormalColumn normalColumn = (NormalColumn) fromColumn;\n final NormalColumn copyColumn = new CopyColumn(normalColumn);\n if (normalColumn.getWord() != null) {\n copyColumn.setWord(new CopyWord(normalColumn.getWord()));\n }\n columns.add(copyColumn);\n } else {\n columns.add(fromColumn);\n }\n }\n to.setColumns(columns);\n to.setOutgoing(getOutgoings());\n to.setIncoming(getIncomings());\n return to;\n }\n public abstract TableView copyData();\n // Restructure\n public void restructureData(TableView to) {\n final Dictionary dictionary = this.getDiagram().getDiagramContents().getDictionary();\n to.setPhysicalName(this.getPhysicalName());\n to.setLogicalName(this.getLogicalName());\n to.setDescription(this.getDescription());\n if (getColor() != null) {\n to.setColor(this.getColor()[0], this.getColor()[1], this.getColor()[2]);\n }\n for (final NormalColumn toColumn : to.getNormalColumns()) {\n dictionary.remove(toColumn);\n }\n final List<ERColumn> columns = new ArrayList<>();\n final List<NormalColumn> newPrimaryKeyColumns = new ArrayList<>();\n for (final ERColumn fromColumn : getColumns()) {\n if (columns.stream().anyMatch(c -> c.same(fromColumn))) {\n continue;\n }\n if (fromColumn instanceof NormalColumn) {\n final CopyColumn copyColumn = (CopyColumn) fromColumn;\n CopyWord copyWord = copyColumn.getWord();\n if (copyColumn.isForeignKey()) {\n copyWord = null;\n }\n if (copyWord != null) {\n final Word originalWord = copyColumn.getOriginalWord();\n dictionary.copyTo(copyWord, originalWord);\n }\n final NormalColumn restructuredColumn = copyColumn.getRestructuredColumn();\n restructuredColumn.setColumnHolder(this);\n if (copyWord == null) {\n restructuredColumn.setWord(null);\n }\n columns.add(restructuredColumn);\n if (restructuredColumn.isPrimaryKey()) {\n newPrimaryKeyColumns.add(restructuredColumn);\n }\n dictionary.add(restructuredColumn);\n } else {\n columns.add(fromColumn);\n }\n }\n this.setTargetTableRelation(to, newPrimaryKeyColumns);\n to.setColumns(columns);\n }\n // Relationship\n private void setTargetTableRelation(TableView sourceTable, List<NormalColumn> newPrimaryKeyColumns) {\n for (final Relationship relationship : sourceTable.getOutgoingRelationshipList()) {\n if (relationship.isReferenceForPK()) {\n final TableView targetTable = relationship.getTargetTableView();\n final List<NormalColumn> foreignKeyColumns = relationship.getForeignKeyColumns();\n boolean isPrimary = true;\n boolean isPrimaryChanged = false;\n for (final NormalColumn primaryKeyColumn : newPrimaryKeyColumns) {\n boolean isReferenced = false;\n for (final Iterator<NormalColumn> iter = foreignKeyColumns.iterator(); iter.hasNext();) {\n final NormalColumn foreignKeyColumn = iter.next();\n if (isPrimary) {\n isPrimary = foreignKeyColumn.isPrimaryKey();\n }\n for (final NormalColumn referencedColumn : foreignKeyColumn.getReferencedColumnList()) {\n if (referencedColumn == primaryKeyColumn) {\n isReferenced = true;\n iter.remove();\n break;\n }\n }\n if (isReferenced) {\n break;\n }\n }\n if (!isReferenced) {\n if (isPrimary) {\n isPrimaryChanged = true;\n }\n final NormalColumn foreignKeyColumn = new NormalColumn(primaryKeyColumn, primaryKeyColumn, relationship, isPrimary);\n targetTable.addColumn(foreignKeyColumn);\n }\n }\n for (final NormalColumn removedColumn : foreignKeyColumns) {\n if (removedColumn.isPrimaryKey()) {\n isPrimaryChanged = true;\n }\n targetTable.removeColumn(removedColumn);\n }\n if (isPrimaryChanged) {\n final List<NormalColumn> nextNewPrimaryKeyColumns = ((ERTable) targetTable).getPrimaryKeys();\n this.setTargetTableRelation(targetTable, nextNewPrimaryKeyColumns);\n }\n targetTable.setDirty();\n }\n }\n }\n public List<Relationship> getIncomingRelationshipList() {\n final List<Relationship> relations = new ArrayList<>();\n for (final WalkerConnection connection : getIncomings()) {\n if (connection instanceof Relationship) {\n relations.add((Relationship) connection);\n }\n }\n return relations;\n }\n public List<Relationship> getOutgoingRelationshipList() {\n final List<Relationship> relations = new ArrayList<>();\n for (final WalkerConnection connection : getOutgoings()) {\n if (connection instanceof Relationship) {\n relations.add((Relationship) connection);\n }\n }\n Collections.sort(relations);\n return relations;\n }\n // Column Group\n public void replaceColumnGroup(ColumnGroup oldColumnGroup, ColumnGroup newColumnGroup) {\n final int index = this.columns.indexOf(oldColumnGroup);\n if (index != -1) {\n this.columns.remove(index);\n this.columns.add(index, newColumnGroup);\n }\n }\n // Name with Schema\n public String getNameWithSchema(String database) {\n final StringBuilder sb = new StringBuilder();\n final DBManager dbManager = DBManagerFactory.getDBManager(database);\n if (!dbManager.isSupported(DBManager.SUPPORT_SCHEMA)) {\n return Format.null2blank(this.getPhysicalName());\n }\n final TableViewProperties tableViewProperties = this.getDiagram().getDiagramContents().getSettings().getTableViewProperties();\n String schema = this.tableViewProperties.getSchema();\n if (schema == null || schema.equals(\"\")) {\n schema = tableViewProperties.getSchema();\n }\n if (schema != null && !schema.equals(\"\")) {\n sb.append(schema);\n sb.append(\".\");\n }\n sb.append(this.getPhysicalName());\n return sb.toString();\n }\n // TableView ID\n public String buildTableViewId() {\n return getIdPrefix() + \".\" + getPhysicalName();\n }\n protected abstract String getIdPrefix();\n // Basic Override\n @Override\n public int compareTo(TableView other) {\n return PHYSICAL_NAME_COMPARATOR.compare(this, other);\n }\n private static class TableViewPhysicalNameComparator implements Comparator<TableView> {\n @Override\n public int compare(TableView o1, TableView o2) {\n if (o1 == o2) {\n return 0;\n }\n if (o2 == null) {\n return -1;\n }\n if (o1 == null) {\n return 1;\n }\n final String schema1 = o1.getTableViewProperties().getSchema();\n final String schema2 = o2.getTableViewProperties().getSchema();\n final int compareTo = Format.null2blank(schema1).toUpperCase().compareTo(Format.null2blank(schema2).toUpperCase());\n if (compareTo != 0) {\n return compareTo;\n }\n int value = Format.null2blank(o1.physicalName).toUpperCase().compareTo(Format.null2blank(o2.physicalName).toUpperCase());\n if (value != 0) {\n return value;\n }\n value = Format.null2blank(o1.logicalName).toUpperCase().compareTo(Format.null2blank(o2.logicalName).toUpperCase());\n if (value != 0) {\n return value;\n }\n return 0;\n }\n }\n private static class TableViewLogicalNameComparator implements Comparator<TableView> {\n @Override\n public int compare(TableView o1, TableView o2) {\n if (o1 == o2) {\n return 0;\n }\n if (o2 == null) {\n return -1;\n }\n if (o1 == null) {\n return 1;\n }\n final String schema1 = o1.getTableViewProperties().getSchema();\n final String schema2 = o2.getTableViewProperties().getSchema();\n final int compareTo = Format.null2blank(schema1).toUpperCase().compareTo(Format.null2blank(schema2).toUpperCase());\n if (compareTo != 0) {\n return compareTo;\n }\n int value = Format.null2blank(o1.logicalName).toUpperCase().compareTo(Format.null2blank(o2.logicalName).toUpperCase());\n if (value != 0) {\n return value;\n }\n value = Format.null2blank(o1.physicalName).toUpperCase().compareTo(Format.null2blank(o2.physicalName).toUpperCase());\n if (value != 0) {\n return value;\n }\n return 0;\n }\n }\n @Override\n public boolean isUsePersistentId() {\n return false;\n }\n @Override\n public boolean isIndenpendentOnModel() {\n return false;\n }\n // Accessor\n public String getPhysicalName() {\n return physicalName;\n }\n public void setPhysicalName(String physicalName) {\n final String old = this.physicalName;\n this.physicalName = physicalName;\n this.firePropertyChange(PROPERTY_CHANGE_PHYSICAL_NAME, old, physicalName);\n }\n public String getLogicalName() {\n return logicalName;\n }\n public void setLogicalName(String logicalName) {\n final String old = this.logicalName;\n this.logicalName = logicalName;\n this.firePropertyChange(PROPERTY_CHANGE_LOGICAL_NAME, old, logicalName);\n }\n @Override\n public String getName() {\n return this.getPhysicalName(); // #for_erflute change logical to physical for fixed sort\n }\n @Override\n public String getDescription() {\n return description;\n }\n public void setDescription(String description) {\n this.description = description;\n }\n public List<ERColumn> getColumns() {\n return columns;\n }\n public ERColumn getColumn(int index) {\n return this.columns.get(index);\n }\n public void setColumns(List<ERColumn> columns) {\n this.columns = columns;\n for (final ERColumn column : columns) {\n column.setColumnHolder(this);\n }\n firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null);\n }\n public TableViewProperties getTableViewProperties() {\n return tableViewProperties;\n }\n public void changeTableViewProperty(final TableView sourceTableView) {\n sourceTableView.restructureData(this);\n this.getDiagram().changeTable(sourceTableView);\n this.getDiagram().doChangeTable(sourceTableView);\n }\n}"}}},{"rowIdx":1289,"cells":{"answer":{"kind":"string","value":"package ca.uhn.fhir.rest.server.interceptor.auth;\nimport ca.uhn.fhir.context.FhirContext;\nimport ca.uhn.fhir.context.api.AddProfileTagEnum;\nimport ca.uhn.fhir.interceptor.api.HookParams;\nimport ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster;\nimport ca.uhn.fhir.interceptor.api.Pointcut;\nimport ca.uhn.fhir.model.primitive.IdDt;\nimport ca.uhn.fhir.rest.annotation.*;\nimport ca.uhn.fhir.rest.api.Constants;\nimport ca.uhn.fhir.rest.api.*;\nimport ca.uhn.fhir.rest.api.server.RequestDetails;\nimport ca.uhn.fhir.rest.param.ReferenceParam;\nimport ca.uhn.fhir.rest.param.TokenAndListParam;\nimport ca.uhn.fhir.rest.server.FifoMemoryPagingProvider;\nimport ca.uhn.fhir.rest.server.IResourceProvider;\nimport ca.uhn.fhir.rest.server.RestfulServer;\nimport ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;\nimport ca.uhn.fhir.rest.server.interceptor.IServerInterceptor.ActionRequestDetails;\nimport ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;\nimport ca.uhn.fhir.rest.server.tenant.UrlBaseTenantIdentificationStrategy;\nimport ca.uhn.fhir.test.utilities.JettyUtil;\nimport ca.uhn.fhir.util.TestUtil;\nimport ca.uhn.fhir.util.UrlUtil;\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.Lists;\nimport org.apache.commons.io.IOUtils;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.*;\nimport org.apache.http.entity.ContentType;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.conn.PoolingHttpClientConnectionManager;\nimport org.eclipse.jetty.server.Server;\nimport org.eclipse.jetty.servlet.ServletHandler;\nimport org.eclipse.jetty.servlet.ServletHolder;\nimport org.hl7.fhir.instance.model.api.IBaseResource;\nimport org.hl7.fhir.instance.model.api.IIdType;\nimport org.hl7.fhir.r4.model.*;\nimport org.junit.*;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.concurrent.TimeUnit;\nimport static org.apache.commons.lang3.StringUtils.isNotBlank;\nimport static org.hamcrest.Matchers.containsString;\nimport static org.junit.Assert.*;\npublic class AuthorizationInterceptorR4Test {\n private static final String ERR403 = \"{\\\"resourceType\\\":\\\"OperationOutcome\\\",\\\"issue\\\":[{\\\"severity\\\":\\\"error\\\",\\\"code\\\":\\\"processing\\\",\\\"diagnostics\\\":\\\"Access denied by default policy (no applicable rules)\\\"}]}\";\n private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(AuthorizationInterceptorR4Test.class);\n private static CloseableHttpClient ourClient;\n private static String ourConditionalCreateId;\n private static FhirContext ourCtx = FhirContext.forR4();\n private static boolean ourHitMethod;\n private static int ourPort;\n private static List<Resource> ourReturn;\n private static List<IBaseResource> ourDeleted;\n private static Server ourServer;\n private static RestfulServer ourServlet;\n @Before\n public void before() {\n ourCtx.setAddProfileTagWhenEncoding(AddProfileTagEnum.NEVER);\n ourServlet.getInterceptorService().unregisterAllInterceptors();\n ourServlet.setTenantIdentificationStrategy(null);\n ourReturn = null;\n ourDeleted = null;\n ourHitMethod = false;\n ourConditionalCreateId = \"1123\";\n }\n private Resource createCarePlan(Integer theId, String theSubjectId) {\n CarePlan retVal = new CarePlan();\n if (theId != null) {\n retVal.setId(new IdType(\"CarePlan\", (long) theId));\n }\n retVal.setSubject(new Reference(\"Patient/\" + theSubjectId));\n return retVal;\n }\n private Resource createDiagnosticReport(Integer theId, String theSubjectId) {\n DiagnosticReport retVal = new DiagnosticReport();\n if (theId != null) {\n retVal.setId(new IdType(\"DiagnosticReport\", (long) theId));\n }\n retVal.getCode().setText(\"OBS\");\n retVal.setSubject(new Reference(theSubjectId));\n return retVal;\n }\n private HttpEntity createFhirResourceEntity(IBaseResource theResource) {\n String out = ourCtx.newJsonParser().encodeResourceToString(theResource);\n return new StringEntity(out, ContentType.create(Constants.CT_FHIR_JSON, \"UTF-8\"));\n }\n private Resource createObservation(Integer theId, String theSubjectId) {\n Observation retVal = new Observation();\n if (theId != null) {\n retVal.setId(new IdType(\"Observation\", (long) theId));\n }\n retVal.getCode().setText(\"OBS\");\n retVal.setSubject(new Reference(theSubjectId));\n if (theSubjectId != null && theSubjectId.startsWith(\"\n Patient p = new Patient();\n p.setId(theSubjectId);\n p.setActive(true);\n retVal.addContained(p);\n }\n return retVal;\n }\n private Organization createOrganization(int theIndex) {\n Organization retVal = new Organization();\n retVal.setId(\"\" + theIndex);\n retVal.setName(\"Org \" + theIndex);\n return retVal;\n }\n private Resource createPatient(Integer theId) {\n Patient retVal = new Patient();\n if (theId != null) {\n retVal.setId(new IdType(\"Patient\", (long) theId));\n }\n retVal.addName().setFamily(\"FAM\");\n return retVal;\n }\n private Resource createPatient(Integer theId, int theVersion) {\n Resource retVal = createPatient(theId);\n retVal.setId(retVal.getIdElement().withVersion(Integer.toString(theVersion)));\n return retVal;\n }\n private Bundle createTransactionWithPlaceholdersRequestBundle() {\n // Create a input that will be used as a transaction\n Bundle input = new Bundle();\n input.setType(Bundle.BundleType.TRANSACTION);\n String encounterId = \"123-123\";\n String encounterSystem = \"http://our.internal.code.system/encounter\";\n Encounter encounter = new Encounter();\n encounter.addIdentifier(new Identifier().setValue(encounterId)\n .setSystem(encounterSystem));\n encounter.setStatus(Encounter.EncounterStatus.FINISHED);\n Patient p = new Patient()\n .addIdentifier(new Identifier().setValue(\"321-321\").setSystem(\"http://our.internal.code.system/patient\"));\n p.setId(IdDt.newRandomUuid());\n // add patient to input so its created\n input.addEntry()\n .setFullUrl(p.getId())\n .setResource(p)\n .getRequest()\n .setUrl(\"Patient\")\n .setMethod(Bundle.HTTPVerb.POST);\n Reference patientRef = new Reference(p.getId());\n encounter.setSubject(patientRef);\n Condition condition = new Condition()\n .setCode(new CodeableConcept().addCoding(\n new Coding(\"http://hl7.org/fhir/icd-10\", \"S53.40\", \"FOREARM SPRAIN / STRAIN\")))\n .setSubject(patientRef);\n condition.setId(IdDt.newRandomUuid());\n // add condition to input so its created\n input.addEntry()\n .setFullUrl(condition.getId())\n .setResource(condition)\n .getRequest()\n .setUrl(\"Condition\")\n .setMethod(Bundle.HTTPVerb.POST);\n Encounter.DiagnosisComponent dc = new Encounter.DiagnosisComponent();\n dc.setCondition(new Reference(condition.getId()));\n encounter.addDiagnosis(dc);\n CodeableConcept reason = new CodeableConcept();\n reason.setText(\"SLIPPED ON FLOOR,PAIN L) ELBOW\");\n encounter.addReasonCode(reason);\n // add encounter to input so its created\n input.addEntry()\n .setResource(encounter)\n .getRequest()\n .setUrl(\"Encounter\")\n .setIfNoneExist(\"identifier=\" + encounterSystem + \"|\" + encounterId)\n .setMethod(Bundle.HTTPVerb.POST);\n return input;\n }\n private Bundle createTransactionWithPlaceholdersResponseBundle() {\n Bundle output = new Bundle();\n output.setType(Bundle.BundleType.TRANSACTIONRESPONSE);\n output.addEntry()\n .setResource(new Patient().setActive(true)) // don't give this an ID\n .getResponse().setLocation(\"/Patient/1\");\n return output;\n }\n private String extractResponseAndClose(HttpResponse status) throws IOException {\n if (status.getEntity() == null) {\n return null;\n }\n String responseContent;\n responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8);\n IOUtils.closeQuietly(status.getEntity().getContent());\n return responseContent;\n }\n @Test\n public void testAllowAll() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .deny(\"Rule 1\").read().resourcesOfType(Patient.class).withAnyId().andThen()\n .allowAll(\"Default Rule\")\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by rule: Rule 1\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$validate\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testAllowAllForTenant() throws Exception {\n ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .deny(\"Rule 1\").read().resourcesOfType(Patient.class).withAnyId().forTenantIds(\"TENANTA\").andThen()\n .allowAll(\"Default Rule\")\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/Observation/10\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/Patient/1\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by rule: Rule 1\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/Patient/1/$validate\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testAllowByCompartmentUsingUnqualifiedIds() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder().allow().read().resourcesOfType(CarePlan.class).inCompartment(\"Patient\", new IdType(\"Patient/123\")).andThen().denyAll()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n Patient patient;\n CarePlan carePlan;\n // Unqualified\n patient = new Patient();\n patient.setId(\"123\");\n carePlan = new CarePlan();\n carePlan.setStatus(CarePlan.CarePlanStatus.ACTIVE);\n carePlan.getSubject().setResource(patient);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(carePlan);\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Qualified\n patient = new Patient();\n patient.setId(\"Patient/123\");\n carePlan = new CarePlan();\n carePlan.setStatus(CarePlan.CarePlanStatus.ACTIVE);\n carePlan.getSubject().setResource(patient);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(carePlan);\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Wrong one\n patient = new Patient();\n patient.setId(\"456\");\n carePlan = new CarePlan();\n carePlan.setStatus(CarePlan.CarePlanStatus.ACTIVE);\n carePlan.getSubject().setResource(patient);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(carePlan);\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n /**\n * #528\n */\n @Test\n public void testAllowByCompartmentWithAnyType() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a\"))\n .andThen().denyAll()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createCarePlan(10, \"845bd9f1-3635-4866-a6c8-1ca085df5c1a\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createCarePlan(10, \"FOO\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testAllowByCompartmentWithAnyTypeWithTenantId() throws Exception {\n ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a\")).forTenantIds(\"TENANTA\")\n .andThen().denyAll()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createCarePlan(10, \"845bd9f1-3635-4866-a6c8-1ca085df5c1a\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createCarePlan(10, \"FOO\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n /**\n * #528\n */\n @Test\n public void testAllowByCompartmentWithType() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder().allow(\"Rule 1\").read().resourcesOfType(CarePlan.class).inCompartment(\"Patient\", new IdType(\"Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a\")).andThen().denyAll()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createCarePlan(10, \"845bd9f1-3635-4866-a6c8-1ca085df5c1a\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createCarePlan(10, \"FOO\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testBatchWhenOnlyTransactionAllowed() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").transaction().withAnyOperation().andApplyNormalRules().andThen()\n .allow(\"Rule 2\").write().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .build();\n }\n });\n Bundle input = new Bundle();\n input.setType(Bundle.BundleType.BATCH);\n input.addEntry().setResource(createPatient(1)).getRequest().setUrl(\"/Patient\").setMethod(Bundle.HTTPVerb.POST);\n Bundle output = new Bundle();\n output.setType(Bundle.BundleType.TRANSACTIONRESPONSE);\n output.addEntry().getResponse().setLocation(\"/Patient/1\");\n HttpPost httpPost;\n HttpResponse status;\n ourReturn = Collections.singletonList(output);\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(createFhirResourceEntity(input));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n }\n @Test\n public void testBatchWhenTransactionReadDenied() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").transaction().withAnyOperation().andApplyNormalRules().andThen()\n .allow(\"Rule 2\").write().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .build();\n }\n });\n Bundle input = new Bundle();\n input.setType(Bundle.BundleType.BATCH);\n input.addEntry().setResource(createPatient(1)).getRequest().setUrl(\"/Patient\").setMethod(Bundle.HTTPVerb.POST);\n Bundle output = new Bundle();\n output.setType(Bundle.BundleType.TRANSACTIONRESPONSE);\n output.addEntry().setResource(createPatient(2));\n HttpPost httpPost;\n HttpResponse status;\n ourReturn = Collections.singletonList(output);\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(createFhirResourceEntity(input));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n }\n @Test\n public void testBatchWhenTransactionWrongBundleType() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").transaction().withAnyOperation().andApplyNormalRules().andThen()\n .allow(\"Rule 2\").write().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .build();\n }\n });\n Bundle input = new Bundle();\n input.setType(Bundle.BundleType.COLLECTION);\n input.addEntry().setResource(createPatient(1)).getRequest().setUrl(\"/Patient\").setMethod(Bundle.HTTPVerb.POST);\n Bundle output = new Bundle();\n output.setType(Bundle.BundleType.TRANSACTIONRESPONSE);\n output.addEntry().setResource(createPatient(1));\n HttpPost httpPost;\n HttpResponse status;\n String response;\n ourReturn = Collections.singletonList(output);\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(createFhirResourceEntity(input));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(422, status.getStatusLine().getStatusCode());\n }\n @Test\n public void testDeleteByCompartment() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").delete().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").delete().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n });\n HttpDelete httpDelete;\n HttpResponse status;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpDelete = new HttpDelete(\"http://localhost:\" + ourPort + \"/Patient/2\");\n status = ourClient.execute(httpDelete);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(1));\n httpDelete = new HttpDelete(\"http://localhost:\" + ourPort + \"/Patient/1\");\n status = ourClient.execute(httpDelete);\n extractResponseAndClose(status);\n assertEquals(204, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testDeleteByCompartmentUsingTransaction() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").delete().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").delete().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow().transaction().withAnyOperation().andApplyNormalRules().andThen()\n .build();\n }\n });\n HttpPost httpPost;\n HttpResponse status;\n String responseString;\n Bundle responseBundle = new Bundle();\n responseBundle.setType(Bundle.BundleType.TRANSACTIONRESPONSE);\n Bundle bundle = new Bundle();\n bundle.setType(Bundle.BundleType.TRANSACTION);\n ourHitMethod = false;\n bundle.getEntry().clear();\n ourReturn = Collections.singletonList(responseBundle);\n ourDeleted = Collections.singletonList(createPatient(2));\n bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl(\"Patient/2\");\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8)));\n status = ourClient.execute(httpPost);\n responseString = extractResponseAndClose(status);\n assertEquals(responseString, 403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n bundle.getEntry().clear();\n bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl(\"Patient/1\");\n ourReturn = Collections.singletonList(responseBundle);\n ourDeleted = Collections.singletonList(createPatient(1));\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8)));\n status = ourClient.execute(httpPost);\n responseString = extractResponseAndClose(status);\n assertEquals(responseString, 200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n bundle.getEntry().clear();\n bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl(\"Observation?subject=Patient/2\");\n ourReturn = Collections.singletonList(responseBundle);\n ourDeleted = Collections.singletonList(createObservation(99, \"Patient/2\"));\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8)));\n status = ourClient.execute(httpPost);\n responseString = extractResponseAndClose(status);\n assertEquals(responseString, 403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n bundle.getEntry().clear();\n bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl(\"Observation?subject=Patient/1\");\n ourReturn = Collections.singletonList(responseBundle);\n ourDeleted = Collections.singletonList(createObservation(99, \"Patient/1\"));\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8)));\n status = ourClient.execute(httpPost);\n responseString = extractResponseAndClose(status);\n assertEquals(responseString, 200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testDeleteByType() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").delete().resourcesOfType(Patient.class).withAnyId().andThen()\n .build();\n }\n });\n HttpDelete httpDelete;\n HttpResponse status;\n String responseString;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpDelete = new HttpDelete(\"http://localhost:\" + ourPort + \"/Patient/1\");\n status = ourClient.execute(httpDelete);\n responseString = extractResponseAndClose(status);\n assertEquals(responseString, 204, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpDelete = new HttpDelete(\"http://localhost:\" + ourPort + \"/Observation/1\");\n status = ourClient.execute(httpDelete);\n responseString = extractResponseAndClose(status);\n assertEquals(responseString, 403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n /**\n * #528\n */\n @Test\n public void testDenyActionsNotOnTenant() throws Exception {\n ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.ALLOW) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder().denyAll().notForTenantIds(\"TENANTA\", \"TENANTB\").build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/Patient/1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTC/Patient/1\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by rule: (unnamed rule)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testDenyAll() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow().read().resourcesOfType(Patient.class).withAnyId().andThen()\n .denyAll(\"Default Rule\")\n .build();\n }\n @Override\n protected void handleDeny(Verdict decision) {\n // Make sure the toString() method on Verdict never fails\n ourLog.info(\"Denying with decision: {}\", decision);\n super.handleDeny(decision);\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by rule: Default Rule\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$validate\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by rule: Default Rule\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by rule: Default Rule\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testDenyAllByDefault() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow().read().resourcesOfType(Patient.class).withAnyId().andThen()\n .build();\n }\n @Override\n protected void handleDeny(Verdict decision) {\n // Make sure the toString() method on Verdict never fails\n ourLog.info(\"Denying with decision: {}\", decision);\n super.handleDeny(decision);\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$validate\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n /**\n * #528\n */\n @Test\n public void testDenyByCompartmentWithAnyType() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder().deny(\"Rule 1\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a\")).andThen().allowAll().build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createCarePlan(10, \"845bd9f1-3635-4866-a6c8-1ca085df5c1a\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createCarePlan(10, \"FOO\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n /**\n * #528\n */\n @Test\n public void testDenyByCompartmentWithType() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder().deny(\"Rule 1\").read().resourcesOfType(CarePlan.class).inCompartment(\"Patient\", new IdType(\"Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a\")).andThen().allowAll()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createCarePlan(10, \"845bd9f1-3635-4866-a6c8-1ca085df5c1a\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createCarePlan(10, \"FOO\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/135154\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testHistoryWithReadAll() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().allResources().withAnyId()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourReturn = Collections.singletonList(createPatient(2, 1));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/_history\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/_history\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/_history\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testInvalidInstanceIds() {\n try {\n new RuleBuilder().allow(\"Rule 1\").write().instance((String) null);\n fail();\n } catch (NullPointerException e) {\n assertEquals(\"theId must not be null or empty\", e.getMessage());\n }\n try {\n new RuleBuilder().allow(\"Rule 1\").write().instance(\"\");\n fail();\n } catch (IllegalArgumentException e) {\n assertEquals(\"theId must not be null or empty\", e.getMessage());\n }\n try {\n new RuleBuilder().allow(\"Rule 1\").write().instance(\"Observation/\");\n fail();\n } catch (IllegalArgumentException e) {\n assertEquals(\"theId must contain an ID part\", e.getMessage());\n }\n try {\n new RuleBuilder().allow(\"Rule 1\").write().instance(new IdType());\n fail();\n } catch (NullPointerException e) {\n assertEquals(\"theId.getValue() must not be null or empty\", e.getMessage());\n }\n try {\n new RuleBuilder().allow(\"Rule 1\").write().instance(new IdType(\"\"));\n fail();\n } catch (NullPointerException e) {\n assertEquals(\"theId.getValue() must not be null or empty\", e.getMessage());\n }\n try {\n new RuleBuilder().allow(\"Rule 1\").write().instance(new IdType(\"Observation\", (String) null));\n fail();\n } catch (NullPointerException e) {\n assertEquals(\"theId must contain an ID part\", e.getMessage());\n }\n }\n @Test\n public void testMetadataAllow() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").metadata()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/metadata\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n }\n @Test\n public void testMetadataDeny() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.ALLOW) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .deny(\"Rule 1\").metadata()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/metadata\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n }\n @Test\n public void testOperationAnyName() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().withAnyName().onServer().andRequireExplicitResponseAuthorization().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n // Server\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n String response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testOperationAppliesAtAnyLevel() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().named(\"opName\").atAnyLevel().andRequireExplicitResponseAuthorization().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Server\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Instance Version\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/_history/2/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testOperationAppliesAtAnyLevelWrongOpName() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().named(\"opNameBadOp\").atAnyLevel().andRequireExplicitResponseAuthorization().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Server\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Instance Version\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/_history/2/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testOperationByInstanceOfTypeAllowed() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").operation().named(\"everything\").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = new ArrayList<>();\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$everything\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Bundle\"));\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertEquals(true, ourHitMethod);\n ourReturn = new ArrayList<>();\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Encounter/1/$everything\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"OperationOutcome\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(false, ourHitMethod);\n }\n @Test\n public void testOperationByInstanceOfTypeWithInvalidReturnValue() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").operation().named(\"everything\").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization().andThen()\n .allow(\"Rule 2\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // With a return value we don't allow\n ourReturn = Collections.singletonList(createPatient(222));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$everything\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"OperationOutcome\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(true, ourHitMethod);\n // With a return value we do\n ourReturn = Collections.singletonList(createPatient(1));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$everything\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Bundle\"));\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertEquals(true, ourHitMethod);\n }\n @Test\n public void testOperationByInstanceOfTypeWithReturnValue() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").operation().named(\"everything\").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = new ArrayList<>();\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$everything\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Bundle\"));\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertEquals(true, ourHitMethod);\n ourReturn = new ArrayList<>();\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Encounter/1/$everything\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"OperationOutcome\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(false, ourHitMethod);\n }\n @Test\n public void testOperationInstanceLevel() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().named(\"opName\").onInstance(new IdType(\"http://example.com/Patient/1/_history/2\")).andRequireExplicitResponseAuthorization().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Server\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Wrong instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/2/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testOperationInstanceLevelAnyInstance() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().named(\"opName\").onAnyInstance().andRequireExplicitResponseAuthorization().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Server\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Another Instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/2/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Wrong name\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/2/$opName2\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testOperationNotAllowedWithWritePermissiom() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").write().allResources().withAnyId().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Server\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // System\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/123/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testOperationServerLevel() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().named(\"opName\").onServer().andRequireExplicitResponseAuthorization().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Server\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testOperationTypeLevel() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().named(\"opName\").onType(Patient.class).andRequireExplicitResponseAuthorization().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Server\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Wrong type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Wrong name\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$opName2\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testOperationTypeLevelWildcard() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().named(\"opName\").onAnyType().andRequireExplicitResponseAuthorization().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Server\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Another type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Wrong name\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/$opName2\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testOperationTypeLevelWithOperationMethodHavingOptionalIdParam() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().named(\"opName\").onType(Organization.class).andRequireExplicitResponseAuthorization().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Server\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Organization/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createOrganization(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Organization/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Wrong type\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createOrganization(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n // Instance\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createOrganization(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Organization/1/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testOperationTypeLevelWithTenant() throws Exception {\n ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().named(\"opName\").onType(Patient.class).andRequireExplicitResponseAuthorization().forTenantIds(\"TENANTA\").andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Right Tenant\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/Patient/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Wrong Tenant\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTC/Patient/$opName\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Access denied by default policy\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testOperationTypeLevelDifferentBodyType() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"RULE 1\").operation().named(\"process-message\").onServer().andRequireExplicitResponseAuthorization().andThen()\n .build();\n }\n });\n HttpPost httpPost;\n HttpResponse status;\n String response;\n Bundle input = new Bundle();\n input.setType(Bundle.BundleType.MESSAGE);\n String inputString = ourCtx.newJsonParser().encodeResourceToString(input);\n // With body\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/$process-message\");\n httpPost.setEntity(new StringEntity(inputString, ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8)));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // With body\n ourHitMethod = false;\n HttpGet httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/$process-message\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testOperationWithTester() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").operation().named(\"everything\").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization().withTester(new IAuthRuleTester() {\n @Override\n public boolean matches(RestOperationTypeEnum theOperation, RequestDetails theRequestDetails, IIdType theInputResourceId, IBaseResource theInputResource) {\n return theInputResourceId.getIdPart().equals(\"1\");\n }\n })\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = new ArrayList<>();\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$everything\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Bundle\"));\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertEquals(true, ourHitMethod);\n ourReturn = new ArrayList<>();\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/2/$everything\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"OperationOutcome\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(false, ourHitMethod);\n }\n @Test\n public void testPatchAllowed() throws IOException {\n Observation obs = new Observation();\n obs.setSubject(new Reference(\"Patient/999\"));\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow().patch().allRequests().andThen()\n .build();\n }\n });\n String patchBody = \"[\\n\" +\n \" { \\\"op\\\": \\\"replace\\\", \\\"path\\\": \\\"Observation/status\\\", \\\"value\\\": \\\"amended\\\" }\\n\" +\n \" ]\";\n HttpPatch patch = new HttpPatch(\"http://localhost:\" + ourPort + \"/Observation/123\");\n patch.setEntity(new StringEntity(patchBody, ContentType.create(Constants.CT_JSON_PATCH, Charsets.UTF_8)));\n CloseableHttpResponse status = ourClient.execute(patch);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testPatchNotAllowed() throws IOException {\n Observation obs = new Observation();\n obs.setSubject(new Reference(\"Patient/999\"));\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow().metadata().andThen()\n .build();\n }\n });\n String patchBody = \"[\\n\" +\n \" { \\\"op\\\": \\\"replace\\\", \\\"path\\\": \\\"Observation/status\\\", \\\"value\\\": \\\"amended\\\" }\\n\" +\n \" ]\";\n HttpPatch patch = new HttpPatch(\"http://localhost:\" + ourPort + \"/Observation/123\");\n patch.setEntity(new StringEntity(patchBody, ContentType.create(Constants.CT_JSON_PATCH, Charsets.UTF_8)));\n CloseableHttpResponse status = ourClient.execute(patch);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testGraphQLAllowed() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").graphQL().any().andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$graphql?query=\" + UrlUtil.escapeUrlParam(\"{name}\"));\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testGraphQLDenied() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/$graphql?query=\" + UrlUtil.escapeUrlParam(\"{name}\"));\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testReadByAnyId() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().resourcesOfType(Patient.class).withAnyId()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/_history/222\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourReturn = Arrays.asList(createPatient(1), createObservation(10, \"Patient/2\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Arrays.asList(createPatient(2), createObservation(10, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testReadByAnyIdWithTenantId() throws Exception {\n ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().resourcesOfType(Patient.class).withAnyId().forTenantIds(\"TENANTA\")\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/Patient/1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTB/Patient/1\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/Patient/1/_history/222\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourReturn = Arrays.asList(createPatient(1), createObservation(10, \"Patient/2\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/Patient\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Arrays.asList(createPatient(2), createObservation(10, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/TENANTA/Patient\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testReadByAnyIdWithTester() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().resourcesOfType(Patient.class).withAnyId().withTester(new IAuthRuleTester() {\n @Override\n public boolean matches(RestOperationTypeEnum theOperation, RequestDetails theRequestDetails, IIdType theInputResourceId, IBaseResource theInputResource) {\n return theInputResourceId != null && theInputResourceId.getIdPart().equals(\"1\");\n }\n })\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1/_history/222\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourReturn = Arrays.asList(createPatient(1), createObservation(10, \"Patient/2\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testReadByCompartmentReadByIdParam() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourReturn = Collections.singletonList(createPatient(1));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient?_id=Patient/1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createPatient(1));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient?_id=1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient?_id=Patient/2\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testReadByCompartmentReadByPatientParam() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourReturn = Collections.singletonList(createDiagnosticReport(1, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/DiagnosticReport?patient=Patient/1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createDiagnosticReport(1, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/DiagnosticReport?patient=1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createDiagnosticReport(1, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/DiagnosticReport?patient=Patient/2\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourReturn = Collections.singletonList(createDiagnosticReport(1, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/DiagnosticReport?subject=Patient/1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createDiagnosticReport(1, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/DiagnosticReport?subject=1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createDiagnosticReport(1, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/DiagnosticReport?subject=Patient/2\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testReadByCompartmentRight() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").read().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n ourReturn = Collections.singletonList(createPatient(1));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Arrays.asList(createPatient(1), createObservation(10, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testReadByCompartmentWrongAllTypesProactiveBlockEnabledNoResponse() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .build();\n }\n }.setFlags());\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = Collections.emptyList();\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/2\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(404, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(404, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/_history\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/_history\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/999/_history\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testReadByCompartmentWrongProactiveBlockDisabled() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").read().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n }.setFlags(AuthorizationFlagsEnum.NO_NOT_PROACTIVELY_BLOCK_COMPARTMENT_READ_ACCESS));\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/2\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourReturn = Collections.singletonList(createObservation(10, \"Patient/2\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createCarePlan(10, \"Patient/2\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourReturn = Arrays.asList(createPatient(1), createObservation(10, \"Patient/2\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Arrays.asList(createPatient(2), createObservation(10, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertThat(response, containsString(\"Access denied by default policy (no applicable rules)\"));\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testReadByCompartmentWrongProactiveBlockDisabledNoResponse() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").read().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n }.setFlags(AuthorizationFlagsEnum.NO_NOT_PROACTIVELY_BLOCK_COMPARTMENT_READ_ACCESS));\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = Collections.emptyList();\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/2\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(404, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testReadByCompartmentWrongProactiveBlockEnabledNoResponse() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").read().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n }.setFlags());\n HttpGet httpGet;\n HttpResponse status;\n String response;\n ourReturn = Collections.emptyList();\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/2\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(404, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // CarePlan could potentially be in the Patient/1 compartment but we don't\n // have any rules explicitly allowing CarePlan so it's blocked\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/CarePlan/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/_history\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/_history\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/999/_history\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testReadByCompartmentDoesntAllowContained() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 2\").read().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n }.setFlags());\n HttpGet httpGet;\n HttpResponse status;\n String response;\n // Read with allowed subject\n ourReturn = Lists.newArrayList(createObservation(10, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Read with contained\n ourReturn = Lists.newArrayList(createObservation(10, \"\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Read with contained\n Observation obs = (Observation) createObservation(10, null);\n obs.setSubject(new Reference(new Patient().setActive(true)));\n ourReturn = Lists.newArrayList(obs);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/10\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testReadByInstance() throws Exception {\n ourConditionalCreateId = \"1\";\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().instance(\"Observation/900\").andThen()\n .allow(\"Rule 1\").read().instance(\"901\").andThen()\n .build();\n }\n });\n HttpResponse status;\n String response;\n HttpGet httpGet;\n ourReturn = Collections.singletonList(createObservation(900, \"Patient/1\"));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation/900\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createPatient(901));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/901\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourReturn = Collections.singletonList(createPatient(1));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient/1?_format=json\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n }\n @Test\n public void testReadByInstanceAllowsTargetedSearch() throws Exception {\n ourConditionalCreateId = \"1\";\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n RuleBuilder ruleBuilder = new RuleBuilder();\n ruleBuilder.allow().read().instance(\"Patient/900\").andThen();\n ruleBuilder.allow().read().instance(\"Patient/700\").andThen();\n return ruleBuilder.build();\n }\n });\n HttpResponse status;\n String response;\n HttpGet httpGet;\n ourReturn = Collections.singletonList(createPatient(900));\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient?_id=900\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient?_id=Patient/900\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient?_id=901\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient?_id=Patient/901\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n // technically this is invalid, but just in case..\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation?_id=Patient/901\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation?_id=901\");\n status = ourClient.execute(httpGet);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient?_id=Patient/900,Patient/700\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Patient?_id=900,777\");\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testReadPageRight() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String respString;\n Bundle respBundle;\n ourReturn = new ArrayList<>();\n for (int i = 0; i < 10; i++) {\n ourReturn.add(createObservation(i, \"Patient/1\"));\n }\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation?_count=5&_format=json&subject=Patient/1\");\n status = ourClient.execute(httpGet);\n respString = extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n respBundle = ourCtx.newJsonParser().parseResource(Bundle.class, respString);\n Assert.assertEquals(5, respBundle.getEntry().size());\n Assert.assertEquals(10, respBundle.getTotal());\n Assert.assertEquals(\"Observation/0\", respBundle.getEntry().get(0).getResource().getIdElement().toUnqualifiedVersionless().getValue());\n assertNotNull(respBundle.getLink(\"next\"));\n // Load next page\n ourHitMethod = false;\n httpGet = new HttpGet(respBundle.getLink(\"next\").getUrl());\n status = ourClient.execute(httpGet);\n respString = extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n respBundle = ourCtx.newJsonParser().parseResource(Bundle.class, respString);\n Assert.assertEquals(5, respBundle.getEntry().size());\n Assert.assertEquals(10, respBundle.getTotal());\n Assert.assertEquals(\"Observation/5\", respBundle.getEntry().get(0).getResource().getIdElement().toUnqualifiedVersionless().getValue());\n assertNull(respBundle.getLink(\"next\"));\n }\n @Test\n public void testReadPageWrong() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").read().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n });\n HttpGet httpGet;\n HttpResponse status;\n String respString;\n Bundle respBundle;\n ourReturn = new ArrayList<>();\n for (int i = 0; i < 5; i++) {\n ourReturn.add(createObservation(i, \"Patient/1\"));\n }\n for (int i = 5; i < 10; i++) {\n ourReturn.add(createObservation(i, \"Patient/2\"));\n }\n ourHitMethod = false;\n httpGet = new HttpGet(\"http://localhost:\" + ourPort + \"/Observation?_count=5&_format=json&subject=Patient/1\");\n status = ourClient.execute(httpGet);\n respString = extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n respBundle = ourCtx.newJsonParser().parseResource(Bundle.class, respString);\n Assert.assertEquals(5, respBundle.getEntry().size());\n Assert.assertEquals(10, respBundle.getTotal());\n Assert.assertEquals(\"Observation/0\", respBundle.getEntry().get(0).getResource().getIdElement().toUnqualifiedVersionless().getValue());\n assertNotNull(respBundle.getLink(\"next\"));\n // Load next page\n ourHitMethod = false;\n httpGet = new HttpGet(respBundle.getLink(\"next\").getUrl());\n status = ourClient.execute(httpGet);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testTransactionWithSearch() throws IOException {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"transactions\").transaction().withAnyOperation().andApplyNormalRules().andThen()\n .allow(\"read patient\").read().resourcesOfType(Patient.class).withAnyId().andThen()\n .denyAll(\"deny all\")\n .build();\n }\n });\n // Request is a transaction with 1 search\n Bundle requestBundle = new Bundle();\n requestBundle.setType(Bundle.BundleType.TRANSACTION);\n String patientId = \"10000003857\";\n Bundle.BundleEntryComponent bundleEntryComponent = requestBundle.addEntry();\n Bundle.BundleEntryRequestComponent bundleEntryRequestComponent = new Bundle.BundleEntryRequestComponent();\n bundleEntryRequestComponent.setMethod(Bundle.HTTPVerb.GET);\n bundleEntryRequestComponent.setUrl(ResourceType.Patient + \"?identifier=\" + patientId);\n bundleEntryComponent.setRequest(bundleEntryRequestComponent);\n /*\n * Response is a transaction response containing the search results\n */\n Bundle searchResponseBundle = new Bundle();\n Patient patent = new Patient();\n patent.setActive(true);\n patent.setId(\"Patient/123\");\n searchResponseBundle.addEntry().setResource(patent);\n Bundle responseBundle = new Bundle();\n responseBundle\n .addEntry()\n .setResource(searchResponseBundle);\n ourReturn = Collections.singletonList(responseBundle);\n HttpPost httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(createFhirResourceEntity(requestBundle));\n CloseableHttpResponse status = ourClient.execute(httpPost);\n String resp = extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n }\n @Test\n public void testTransactionWithNoBundleType() throws IOException {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"transactions\").transaction().withAnyOperation().andApplyNormalRules().andThen()\n .allow(\"read patient\").read().resourcesOfType(Patient.class).withAnyId().andThen()\n .denyAll(\"deny all\")\n .build();\n }\n });\n // Request is a transaction with 1 search\n Bundle requestBundle = new Bundle();\n String patientId = \"10000003857\";\n Bundle.BundleEntryComponent bundleEntryComponent = requestBundle.addEntry();\n Bundle.BundleEntryRequestComponent bundleEntryRequestComponent = new Bundle.BundleEntryRequestComponent();\n bundleEntryRequestComponent.setMethod(Bundle.HTTPVerb.GET);\n bundleEntryRequestComponent.setUrl(ResourceType.Patient + \"?identifier=\" + patientId);\n bundleEntryComponent.setRequest(bundleEntryRequestComponent);\n HttpPost httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(createFhirResourceEntity(requestBundle));\n CloseableHttpResponse status = ourClient.execute(httpPost);\n String resp = extractResponseAndClose(status);\n assertEquals(422, status.getStatusLine().getStatusCode());\n assertThat(resp, containsString(\"Invalid request Bundle.type value for transaction: \\\\\\\"\\\\\\\"\"));\n }\n /**\n * See #762\n */\n @Test\n public void testTransactionWithPlaceholderIdsResponseAuthorized() throws IOException {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"transactions\").transaction().withAnyOperation().andApplyNormalRules().andThen()\n .allow(\"read patient\").read().resourcesOfType(Patient.class).withAnyId().andThen()\n .allow(\"write patient\").write().resourcesOfType(Patient.class).withAnyId().andThen()\n .allow(\"write encounter\").write().resourcesOfType(Encounter.class).withAnyId().andThen()\n .allow(\"write condition\").write().resourcesOfType(Condition.class).withAnyId().andThen()\n .denyAll(\"deny all\")\n .build();\n }\n });\n Bundle input = createTransactionWithPlaceholdersRequestBundle();\n Bundle output = createTransactionWithPlaceholdersResponseBundle();\n ourReturn = Collections.singletonList(output);\n HttpPost httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(createFhirResourceEntity(input));\n CloseableHttpResponse status = ourClient.execute(httpPost);\n String resp = extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n ourLog.info(resp);\n }\n /**\n * See #762\n */\n @Test\n public void testTransactionWithPlaceholderIdsResponseUnauthorized() throws IOException {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"transactions\").transaction().withAnyOperation().andApplyNormalRules().andThen()\n .allow(\"write patient\").write().resourcesOfType(Patient.class).withAnyId().andThen()\n .allow(\"write encounter\").write().resourcesOfType(Encounter.class).withAnyId().andThen()\n .allow(\"write condition\").write().resourcesOfType(Condition.class).withAnyId().andThen()\n .denyAll(\"deny all\")\n .build();\n }\n });\n Bundle input = createTransactionWithPlaceholdersRequestBundle();\n Bundle output = createTransactionWithPlaceholdersResponseBundle();\n ourReturn = Collections.singletonList(output);\n HttpPost httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(createFhirResourceEntity(input));\n CloseableHttpResponse status = ourClient.execute(httpPost);\n String resp = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n ourLog.info(resp);\n }\n @Test\n public void testTransactionWriteGood() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").transaction().withAnyOperation().andApplyNormalRules().andThen()\n .allow(\"Rule 2\").write().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").read().allResources().inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .build();\n }\n });\n Bundle input = new Bundle();\n input.setType(Bundle.BundleType.TRANSACTION);\n input.addEntry().setResource(createPatient(1)).getRequest().setUrl(\"/Patient\").setMethod(Bundle.HTTPVerb.PUT);\n Bundle output = new Bundle();\n output.setType(Bundle.BundleType.TRANSACTIONRESPONSE);\n output.addEntry().getResponse().setLocation(\"/Patient/1\");\n HttpPost httpPost;\n HttpResponse status;\n ourReturn = Collections.singletonList(output);\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/\");\n httpPost.setEntity(createFhirResourceEntity(input));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n }\n @Test\n public void testWriteByCompartmentCreate() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").write().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 1b\").write().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1123\")).andThen()\n .allow(\"Rule 2\").write().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n });\n HttpEntityEnclosingRequestBase httpPost;\n HttpResponse status;\n String response;\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/Patient\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(null)));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n // Conditional\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/Patient\");\n httpPost.addHeader(\"If-None-Exist\", \"Patient?foo=bar\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(null)));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/Observation\");\n httpPost.setEntity(createFhirResourceEntity(createObservation(null, \"Patient/2\")));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/Observation\");\n httpPost.setEntity(createFhirResourceEntity(createObservation(null, \"Patient/1\")));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(201, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testWriteByCompartmentCreateConditionalResolvesToValid() throws Exception {\n ourConditionalCreateId = \"1\";\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").write().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").createConditional().resourcesOfType(Patient.class)\n .build();\n }\n });\n HttpEntityEnclosingRequestBase httpPost;\n HttpResponse status;\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/Patient\");\n httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, \"foo=bar\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(null)));\n status = ourClient.execute(httpPost);\n String response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(201, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testWriteByCompartmentDeleteConditionalResolvesToValid() throws Exception {\n ourConditionalCreateId = \"1\";\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").delete().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").deleteConditional().resourcesOfType(Patient.class)\n .build();\n }\n });\n HttpDelete httpDelete;\n HttpResponse status;\n ourReturn = Collections.singletonList(createPatient(1));\n ourHitMethod = false;\n httpDelete = new HttpDelete(\"http://localhost:\" + ourPort + \"/Patient?foo=bar\");\n status = ourClient.execute(httpDelete);\n String response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(204, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testWriteByCompartmentDeleteConditionalWithoutDirectMatch() throws Exception {\n ourConditionalCreateId = \"1\";\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 2\").deleteConditional().resourcesOfType(Patient.class).andThen()\n .allow().delete().instance(new IdType(\"Patient/2\")).andThen()\n .build();\n }\n });\n HttpDelete httpDelete;\n HttpResponse status;\n String response;\n // Wrong resource\n ourReturn = Collections.singletonList(createPatient(1));\n ourHitMethod = false;\n httpDelete = new HttpDelete(\"http://localhost:\" + ourPort + \"/Patient?foo=bar\");\n status = ourClient.execute(httpDelete);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Right resource\n ourReturn = Collections.singletonList(createPatient(2));\n ourHitMethod = false;\n httpDelete = new HttpDelete(\"http://localhost:\" + ourPort + \"/Patient?foo=bar\");\n status = ourClient.execute(httpDelete);\n response = extractResponseAndClose(status);\n ourLog.info(response);\n assertEquals(204, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n @Test\n public void testWriteByCompartmentDoesntAllowDelete() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").write().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").write().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n });\n HttpDelete httpDelete;\n HttpResponse status;\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(2));\n httpDelete = new HttpDelete(\"http://localhost:\" + ourPort + \"/Patient/2\");\n status = ourClient.execute(httpDelete);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n ourReturn = Collections.singletonList(createPatient(1));\n httpDelete = new HttpDelete(\"http://localhost:\" + ourPort + \"/Patient/1\");\n status = ourClient.execute(httpDelete);\n extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testWriteByCompartmentUpdate() throws Exception {\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").write().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").write().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\"))\n .build();\n }\n });\n HttpEntityEnclosingRequestBase httpPost;\n String response;\n HttpResponse status;\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Patient/2\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(2)));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(ERR403, response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Patient/1\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(1)));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n // Conditional\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Patient?foo=bar\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(1)));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(ERR403, response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Patient?foo=bar\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(99)));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(ERR403, response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Observation/10\");\n httpPost.setEntity(createFhirResourceEntity(createObservation(10, \"Patient/1\")));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Observation/10\");\n httpPost.setEntity(createFhirResourceEntity(createObservation(10, \"Patient/2\")));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(ERR403, response);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertFalse(ourHitMethod);\n }\n @Test\n public void testWriteByCompartmentUpdateConditionalResolvesToInvalid() throws Exception {\n ourConditionalCreateId = \"1123\";\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").write().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").write().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 3\").updateConditional().resourcesOfType(Patient.class)\n .build();\n }\n });\n HttpEntityEnclosingRequestBase httpPost;\n HttpResponse status;\n String response;\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Patient?foo=bar\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(null)));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertTrue(ourHitMethod);\n }\n @Test\n public void testWriteByCompartmentUpdateConditionalResolvesToValid() throws Exception {\n ourConditionalCreateId = \"1\";\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").write().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").write().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 3\").updateConditional().resourcesOfType(Patient.class)\n .build();\n }\n });\n HttpEntityEnclosingRequestBase httpPost;\n HttpResponse status;\n String response;\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Patient?foo=bar\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(null)));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Observation?foo=bar\");\n httpPost.setEntity(createFhirResourceEntity(createObservation(null, \"Patient/12\")));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n }\n @Test\n public void testWriteByCompartmentUpdateConditionalResolvesToValidAllTypes() throws Exception {\n ourConditionalCreateId = \"1\";\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").write().resourcesOfType(Patient.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 2\").write().resourcesOfType(Observation.class).inCompartment(\"Patient\", new IdType(\"Patient/1\")).andThen()\n .allow(\"Rule 3\").updateConditional().allResources()\n .build();\n }\n });\n HttpEntityEnclosingRequestBase httpPost;\n HttpResponse status;\n String response;\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Patient?foo=bar\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(null)));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Observation?foo=bar\");\n httpPost.setEntity(createFhirResourceEntity(createObservation(null, \"Patient/12\")));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertTrue(ourHitMethod);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n }\n @Test\n public void testWriteByInstance() throws Exception {\n ourConditionalCreateId = \"1\";\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").write().instance(\"Observation/900\").andThen()\n .allow(\"Rule 1\").write().instance(\"901\").andThen()\n .build();\n }\n });\n HttpEntityEnclosingRequestBase httpPost;\n HttpResponse status;\n String response;\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Observation/900\");\n httpPost.setEntity(createFhirResourceEntity(createObservation(900, \"Patient/12\")));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPut(\"http://localhost:\" + ourPort + \"/Observation/901\");\n httpPost.setEntity(createFhirResourceEntity(createObservation(901, \"Patient/12\")));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/Observation\");\n httpPost.setEntity(createFhirResourceEntity(createObservation(null, \"Patient/900\")));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n ourHitMethod = false;\n httpPost = new HttpPost(\"http://localhost:\" + ourPort + \"/Patient\");\n httpPost.setEntity(createFhirResourceEntity(createPatient(null)));\n status = ourClient.execute(httpPost);\n response = extractResponseAndClose(status);\n assertEquals(403, status.getStatusLine().getStatusCode());\n assertEquals(ERR403, response);\n assertFalse(ourHitMethod);\n }\n @Test\n public void testWritePatchByInstance() throws Exception {\n ourConditionalCreateId = \"1\";\n ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {\n @Override\n public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {\n return new RuleBuilder()\n .allow(\"Rule 1\").patch().allRequests().andThen()\n .allow(\"Rule 1\").write().instance(\"Patient/900\").andThen()\n .build();\n }\n });\n HttpEntityEnclosingRequestBase httpPost;\n HttpResponse status;\n String input = \"[ { \\\"op\\\": \\\"replace\\\", \\\"path\\\": \\\"/gender\\\", \\\"value\\\": \\\"male\\\" } ]\";\n ourHitMethod = false;\n httpPost = new HttpPatch(\"http://localhost:\" + ourPort + \"/Patient/900\");\n httpPost.setEntity(new StringEntity(input, ContentType.parse(\"application/json-patch+json\")));\n status = ourClient.execute(httpPost);\n extractResponseAndClose(status);\n assertEquals(200, status.getStatusLine().getStatusCode());\n assertTrue(ourHitMethod);\n }\n public static class DummyCarePlanResourceProvider implements IResourceProvider {\n @Override\n public Class<? extends IBaseResource> getResourceType() {\n return CarePlan.class;\n }\n @Read(version = true)\n public CarePlan read(@IdParam IdType theId) {\n ourHitMethod = true;\n if (ourReturn.isEmpty()) {\n throw new ResourceNotFoundException(theId);\n }\n return (CarePlan) ourReturn.get(0);\n }\n @Search()\n public List<Resource> search() {\n ourHitMethod = true;\n return ourReturn;\n }\n }\n @SuppressWarnings(\"unused\")\n public static class DummyEncounterResourceProvider implements IResourceProvider {\n @Operation(name = \"everything\", idempotent = true)\n public Bundle everything(@IdParam IdType theId) {\n ourHitMethod = true;\n Bundle retVal = new Bundle();\n for (Resource next : ourReturn) {\n retVal.addEntry().setResource(next);\n }\n return retVal;\n }\n @Override\n public Class<? extends IBaseResource> getResourceType() {\n return Encounter.class;\n }\n }\n public static class DummyOrganizationResourceProvider implements IResourceProvider {\n @Override\n public Class<? extends IBaseResource> getResourceType() {\n return Organization.class;\n }\n /**\n * This should come before operation1\n */\n @Operation(name = \"opName\", idempotent = true)\n public Parameters operation0(@IdParam(optional = true) IdType theId) {\n ourHitMethod = true;\n return (Parameters) new Parameters().setId(\"1\");\n }\n }\n public static class DummyDiagnosticReportResourceProvider implements IResourceProvider {\n @Override\n public Class<? extends IBaseResource> getResourceType() {\n return DiagnosticReport.class;\n }\n @Search()\n public List<Resource> search(\n @OptionalParam(name = \"subject\") ReferenceParam theSubject,\n @OptionalParam(name = \"patient\") ReferenceParam thePatient\n ) {\n ourHitMethod = true;\n return ourReturn;\n }\n }\n @SuppressWarnings(\"unused\")\n public static class DummyObservationResourceProvider implements IResourceProvider {\n @Create()\n public MethodOutcome create(@ResourceParam Observation theResource, @ConditionalUrlParam String theConditionalUrl) {\n ourHitMethod = true;\n theResource.setId(\"Observation/1/_history/1\");\n MethodOutcome retVal = new MethodOutcome();\n retVal.setCreated(true);\n retVal.setResource(theResource);\n return retVal;\n }\n @Delete()\n public MethodOutcome delete(@IdParam IdType theId) {\n ourHitMethod = true;\n return new MethodOutcome();\n }\n @Override\n public Class<? extends IBaseResource> getResourceType() {\n return Observation.class;\n }\n /**\n * This should come before operation1\n */\n @Operation(name = \"opName\", idempotent = true)\n public Parameters operation0(@IdParam IdType theId) {\n ourHitMethod = true;\n return (Parameters) new Parameters().setId(\"1\");\n }\n /**\n * This should come after operation0\n */\n @Operation(name = \"opName\", idempotent = true)\n public Parameters operation1() {\n ourHitMethod = true;\n return (Parameters) new Parameters().setId(\"1\");\n }\n @Patch\n public MethodOutcome patch(@IdParam IdType theId, PatchTypeEnum thePatchType, @ResourceParam String theBody) {\n ourHitMethod = true;\n return new MethodOutcome().setId(theId.withVersion(\"2\"));\n }\n @Read(version = true)\n public Observation read(@IdParam IdType theId) {\n ourHitMethod = true;\n if (ourReturn.isEmpty()) {\n throw new ResourceNotFoundException(theId);\n }\n return (Observation) ourReturn.get(0);\n }\n @Search()\n public List<Resource> search(\n @OptionalParam(name = \"_id\") TokenAndListParam theIds,\n @OptionalParam(name = \"subject\") ReferenceParam theSubject) {\n ourHitMethod = true;\n return ourReturn;\n }\n @Update()\n public MethodOutcome update(@IdParam IdType theId, @ResourceParam Observation theResource, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) {\n ourHitMethod = true;\n if (isNotBlank(theConditionalUrl)) {\n IdType actual = new IdType(\"Observation\", ourConditionalCreateId);\n ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, actual);\n subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE);\n theResource.setId(actual);\n } else {\n ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, theResource);\n subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE);\n theResource.setId(theId.withVersion(\"2\"));\n }\n MethodOutcome retVal = new MethodOutcome();\n retVal.setResource(theResource);\n return retVal;\n }\n }\n @SuppressWarnings(\"unused\")\n public static class DummyPatientResourceProvider implements IResourceProvider {\n @Create()\n public MethodOutcome create(@ResourceParam Patient theResource, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) {\n if (isNotBlank(theConditionalUrl)) {\n IdType actual = new IdType(\"Patient\", ourConditionalCreateId);\n ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, actual);\n subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.CREATE);\n } else {\n ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, theResource);\n subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.CREATE);\n }\n ourHitMethod = true;\n theResource.setId(\"Patient/1/_history/1\");\n MethodOutcome retVal = new MethodOutcome();\n retVal.setCreated(true);\n retVal.setResource(theResource);\n return retVal;\n }\n @Delete()\n public MethodOutcome delete(IInterceptorBroadcaster theRequestOperationCallback, @IdParam IdType theId, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) {\n ourHitMethod = true;\n for (IBaseResource next : ourReturn) {\n HookParams params = new HookParams()\n .add(IBaseResource.class, next)\n .add(RequestDetails.class, theRequestDetails)\n .addIfMatchesType(ServletRequestDetails.class, theRequestDetails);\n theRequestOperationCallback.callHooks(Pointcut.STORAGE_PRESTORAGE_RESOURCE_DELETED, params);\n }\n return new MethodOutcome();\n }\n @Operation(name = \"everything\", idempotent = true)\n public Bundle everything(@IdParam IdType theId) {\n ourHitMethod = true;\n Bundle retVal = new Bundle();\n for (Resource next : ourReturn) {\n retVal.addEntry().setResource(next);\n }\n return retVal;\n }\n @Override\n public Class<? extends IBaseResource> getResourceType() {\n return Patient.class;\n }\n @History()\n public List<Resource> history() {\n ourHitMethod = true;\n return (ourReturn);\n }\n @History()\n public List<Resource> history(@IdParam IdType theId) {\n ourHitMethod = true;\n return (ourReturn);\n }\n @Operation(name = \"opName\", idempotent = true)\n public Parameters operation0(@IdParam IdType theId) {\n ourHitMethod = true;\n return (Parameters) new Parameters().setId(\"1\");\n }\n /**\n * More generic method second to make sure that the\n * other method takes precedence\n */\n @Operation(name = \"opName\", idempotent = true)\n public Parameters operation1() {\n ourHitMethod = true;\n return (Parameters) new Parameters().setId(\"1\");\n }\n @Operation(name = \"opName2\", idempotent = true)\n public Parameters operation2(@IdParam IdType theId) {\n ourHitMethod = true;\n return (Parameters) new Parameters().setId(\"1\");\n }\n @Operation(name = \"opName2\", idempotent = true)\n public Parameters operation2() {\n ourHitMethod = true;\n return (Parameters) new Parameters().setId(\"1\");\n }\n @Patch()\n public MethodOutcome patch(@IdParam IdType theId, @ResourceParam String theResource, PatchTypeEnum thePatchType) {\n ourHitMethod = true;\n MethodOutcome retVal = new MethodOutcome();\n return retVal;\n }\n @Read(version = true)\n public Patient read(@IdParam IdType theId) {\n ourHitMethod = true;\n if (ourReturn.isEmpty()) {\n throw new ResourceNotFoundException(theId);\n }\n return (Patient) ourReturn.get(0);\n }\n @Search()\n public List<Resource> search(@OptionalParam(name = \"_id\") TokenAndListParam theIdParam) {\n ourHitMethod = true;\n return ourReturn;\n }\n @Update()\n public MethodOutcome update(@IdParam IdType theId, @ResourceParam Patient theResource, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) {\n ourHitMethod = true;\n if (isNotBlank(theConditionalUrl)) {\n IdType actual = new IdType(\"Patient\", ourConditionalCreateId);\n ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, actual);\n subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE);\n theResource.setId(actual);\n } else {\n ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, theResource);\n subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE);\n theResource.setId(theId.withVersion(\"2\"));\n }\n MethodOutcome retVal = new MethodOutcome();\n retVal.setResource(theResource);\n return retVal;\n }\n @Validate\n public MethodOutcome validate(@ResourceParam Patient theResource, @IdParam IdType theId, @ResourceParam String theRawResource, @ResourceParam EncodingEnum theEncoding,\n @Validate.Mode ValidationModeEnum theMode, @Validate.Profile String theProfile, RequestDetails theRequestDetails) {\n ourHitMethod = true;\n OperationOutcome oo = new OperationOutcome();\n oo.addIssue().setDiagnostics(\"OK\");\n return new MethodOutcome(oo);\n }\n @Validate\n public MethodOutcome validate(@ResourceParam Patient theResource, @ResourceParam String theRawResource, @ResourceParam EncodingEnum theEncoding, @Validate.Mode ValidationModeEnum theMode,\n @Validate.Profile String theProfile, RequestDetails theRequestDetails) {\n ourHitMethod = true;\n OperationOutcome oo = new OperationOutcome();\n oo.addIssue().setDiagnostics(\"OK\");\n return new MethodOutcome(oo);\n }\n }\n public static class PlainProvider {\n @History()\n public List<Resource> history() {\n ourHitMethod = true;\n return (ourReturn);\n }\n @Operation(name = \"opName\", idempotent = true)\n public Parameters operation() {\n ourHitMethod = true;\n return (Parameters) new Parameters().setId(\"1\");\n }\n @Operation(name = \"process-message\", idempotent = true)\n public Parameters processMessage(@OperationParam(name = \"content\") Bundle theInput) {\n ourHitMethod = true;\n return (Parameters) new Parameters().setId(\"1\");\n }\n @GraphQL\n public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQuery String theQuery) {\n ourHitMethod = true;\n return \"{'foo':'bar'}\";\n }\n @Transaction()\n public Bundle search(ServletRequestDetails theRequestDetails, IInterceptorBroadcaster theInterceptorBroadcaster, @TransactionParam Bundle theInput) {\n ourHitMethod = true;\n if (ourDeleted != null) {\n for (IBaseResource next : ourDeleted) {\n HookParams params = new HookParams()\n .add(IBaseResource.class, next)\n .add(RequestDetails.class, theRequestDetails)\n .add(ServletRequestDetails.class, theRequestDetails);\n theInterceptorBroadcaster.callHooks(Pointcut.STORAGE_PRESTORAGE_RESOURCE_DELETED, params);\n }\n }\n return (Bundle) ourReturn.get(0);\n }\n }\n @AfterClass\n public static void afterClassClearContext() throws Exception {\n JettyUtil.closeServer(ourServer);\n TestUtil.clearAllStaticFieldsForUnitTest();\n }\n @BeforeClass\n public static void beforeClass() throws Exception {\n ourServer = new Server(0);\n DummyPatientResourceProvider patProvider = new DummyPatientResourceProvider();\n DummyObservationResourceProvider obsProv = new DummyObservationResourceProvider();\n DummyOrganizationResourceProvider orgProv = new DummyOrganizationResourceProvider();\n DummyEncounterResourceProvider encProv = new DummyEncounterResourceProvider();\n DummyCarePlanResourceProvider cpProv = new DummyCarePlanResourceProvider();\n DummyDiagnosticReportResourceProvider drProv = new DummyDiagnosticReportResourceProvider();\n PlainProvider plainProvider = new PlainProvider();\n ServletHandler proxyHandler = new ServletHandler();\n ourServlet = new RestfulServer(ourCtx);\n ourServlet.setFhirContext(ourCtx);\n ourServlet.setResourceProviders(patProvider, obsProv, encProv, cpProv, orgProv, drProv);\n ourServlet.setPlainProviders(plainProvider);\n ourServlet.setPagingProvider(new FifoMemoryPagingProvider(100));\n ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON);\n ServletHolder servletHolder = new ServletHolder(ourServlet);"}}},{"rowIdx":1290,"cells":{"answer":{"kind":"string","value":"package org.helioviewer.plugins.eveplugin.view;\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.EventQueue;\nimport java.awt.FlowLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.util.Date;\nimport javax.swing.BoxLayout;\nimport javax.swing.ImageIcon;\nimport javax.swing.JButton;\nimport javax.swing.JCheckBox;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport org.helioviewer.base.math.Interval;\nimport org.helioviewer.jhv.gui.IconBank;\nimport org.helioviewer.jhv.gui.IconBank.JHVIcon;\nimport org.helioviewer.jhv.gui.dialogs.observation.ObservationDialog;\nimport org.helioviewer.jhv.layers.LayersListener;\nimport org.helioviewer.jhv.layers.LayersModel;\nimport org.helioviewer.plugins.eveplugin.controller.ZoomController;\nimport org.helioviewer.plugins.eveplugin.events.model.EventModel;\nimport org.helioviewer.plugins.eveplugin.events.model.EventModelListener;\nimport org.helioviewer.plugins.eveplugin.settings.EVESettings;\nimport org.helioviewer.plugins.eveplugin.view.linedataselector.LineDataSelectorPanel;\nimport org.helioviewer.viewmodel.view.View;\n/**\n *\n *\n * @author Bram Bourgoignie (Bram.Bourgoignie@oma.be)\n *\n */\npublic class ControlsPanel extends JPanel implements ActionListener, LayersListener, EventModelListener {\n private static final long serialVersionUID = 3639870635351984819L;\n private static ControlsPanel singletongInstance;\n private final JPanel lineDataSelectorContainer = new JPanel();\n private final ImageIcon addIcon = IconBank.getIcon(JHVIcon.ADD);\n private final JButton addLayerButton = new JButton(\"Add Layer\", addIcon);\n // private final String[] plots = { \"No Events\", \"Events on Plot 1\",\n // \"Events on Plot 2\" };\n // private final JComboBox eventsComboBox = new JComboBox(plots);\n private final JCheckBox eventsCheckBox = new JCheckBox();\n private final JLabel eventsLabel = new JLabel(\"Display events: \");\n private final ImageIcon movietimeIcon = IconBank.getIcon(JHVIcon.LAYER_MOVIE_TIME);\n private final JButton periodFromLayersButton = new JButton(movietimeIcon);\n private ControlsPanel() {\n initVisualComponents();\n LayersModel.getSingletonInstance().addLayersListener(this);\n }\n private void initVisualComponents() {\n EventModel.getSingletonInstance().addEventModelListener(this);\n eventsCheckBox.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n if (eventsCheckBox.isSelected()) {\n EventModel.getSingletonInstance().activateEvents();\n } else {\n EventModel.getSingletonInstance().deactivateEvents();\n }\n }\n });\n addLayerButton.setToolTipText(\"Add a new layer\");\n addLayerButton.addActionListener(this);\n periodFromLayersButton.setToolTipText(\"Request data of selected movie interval\");\n periodFromLayersButton.setPreferredSize(new Dimension(movietimeIcon.getIconWidth() + 14,\n periodFromLayersButton.getPreferredSize().height));\n periodFromLayersButton.addActionListener(this);\n setEnabledStateOfPeriodMovieButton();\n // this.setPreferredSize(new Dimension(100, 300));\n lineDataSelectorContainer.setLayout(new BoxLayout(lineDataSelectorContainer, BoxLayout.Y_AXIS));\n lineDataSelectorContainer.setPreferredSize(new Dimension(100, 130));\n this.setLayout(new BorderLayout());\n add(lineDataSelectorContainer, BorderLayout.CENTER);\n JPanel pageEndPanel = new JPanel();\n pageEndPanel.setBackground(Color.BLUE);\n JPanel flowPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));\n flowPanel.add(eventsLabel);\n flowPanel.add(eventsCheckBox);\n flowPanel.add(periodFromLayersButton);\n flowPanel.add(addLayerButton);\n add(flowPanel, BorderLayout.PAGE_END);\n }\n public static ControlsPanel getSingletonInstance() {\n if (singletongInstance == null) {\n singletongInstance = new ControlsPanel();\n }\n return singletongInstance;\n }\n public void addLineDataSelector(LineDataSelectorPanel lineDataSelectorPanel) {\n lineDataSelectorContainer.add(lineDataSelectorPanel);\n }\n public void removeLineDataSelector(LineDataSelectorPanel lineDataSelectorPanel) {\n lineDataSelectorContainer.remove(lineDataSelectorPanel);\n }\n @Override\n public void actionPerformed(ActionEvent e) {\n if (e.getSource().equals(addLayerButton)) {\n ObservationDialog.getSingletonInstance().showDialog(EVESettings.OBSERVATION_UI_NAME);\n } else if (e.getSource() == periodFromLayersButton) {\n final Interval<Date> interval = new Interval<Date>(LayersModel.getSingletonInstance().getFirstDate(), LayersModel\n .getSingletonInstance().getLastDate());\n ZoomController.getSingletonInstance().setSelectedInterval(interval, true);\n }\n }\n private void setEnabledStateOfPeriodMovieButton() {\n final Interval<Date> frameInterval = LayersModel.getSingletonInstance().getFrameInterval();\n periodFromLayersButton.setEnabled(frameInterval.getStart() != null && frameInterval.getEnd() != null);\n }\n @Override\n public void layerAdded(int idx) {\n if (EventQueue.isDispatchThread()) {\n setEnabledStateOfPeriodMovieButton();\n } else {\n EventQueue.invokeLater(new Runnable() {\n @Override\n public void run() {\n setEnabledStateOfPeriodMovieButton();\n }\n });\n }\n }\n @Override\n public void layerRemoved(View oldView, int oldIdx) {\n if (EventQueue.isDispatchThread()) {\n setEnabledStateOfPeriodMovieButton();\n } else {\n EventQueue.invokeLater(new Runnable() {\n @Override\n public void run() {\n setEnabledStateOfPeriodMovieButton();\n }\n });\n }\n }\n @Override\n public void layerChanged(int idx) {\n // TODO Auto-generated method stub\n }\n @Override\n public void activeLayerChanged(int idx) {\n // TODO Auto-generated method stub\n }\n @Override\n public void viewportGeometryChanged() {\n // TODO Auto-generated method stub\n }\n @Override\n public void timestampChanged(int idx) {\n // TODO Auto-generated method stub\n }\n @Override\n public void subImageDataChanged() {\n // TODO Auto-generated method stub\n }\n @Override\n public void layerDownloaded(int idx) {\n // TODO Auto-generated method stub\n }\n @Override\n public void eventsDeactivated() {\n eventsCheckBox.setSelected(false);\n repaint();\n }\n}"}}},{"rowIdx":1291,"cells":{"answer":{"kind":"string","value":"package com.highcharts.export.pool;\nimport java.net.URL;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.annotation.PostConstruct;\nimport org.apache.log4j.Logger;\nimport com.highcharts.export.server.Server;\nimport com.highcharts.export.server.ServerState;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.util.Enumeration;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport org.apache.commons.io.IOUtils;\npublic class ServerObjectFactory implements ObjectFactory<Server> {\n public String exec;\n public String script;\n private String host;\n private int basePort;\n private int readTimeout;\n private int connectTimeout;\n private int maxTimeout;\n public static String tmpDir = System.getProperty(\"java.io.tmpdir\");\n private static HashMap<Integer, PortStatus> portUsage = new HashMap<Integer, PortStatus>();\n protected static Logger logger = Logger.getLogger(\"pool\");\n private enum PortStatus {\n BUSY,\n FREE;\n }\n @Override\n public Server create() {\n logger.debug(\"in makeObject, \" + exec + \", \" + script + \", \" + host);\n Integer port = this.getAvailablePort();\n portUsage.put(port, PortStatus.BUSY);\n return new Server(exec, script, host, port, connectTimeout, readTimeout, maxTimeout);\n }\n @Override\n public boolean validate(Server server) {\n boolean isValid = false;\n try {\n if(server.getState() != ServerState.IDLE) {\n logger.debug(\"server didn\\'t pass validation\");\n return false;\n }\n String result = server.request(\"{\\\"status\\\":\\\"isok\\\"}\");\n if(result.indexOf(\"OK\") > -1) {\n isValid = true;\n logger.debug(\"server passed validation\");\n } else {\n logger.debug(\"server didn\\'t pass validation\");\n }\n } catch (Exception e) {\n logger.error(\"Error while validating object in Pool: \" + e.getMessage());\n }\n return isValid;\n }\n @Override\n public void destroy(Server server) {\n ServerObjectFactory.releasePort(server.getPort());\n server.cleanup();\n }\n @Override\n public void activate(Server server) {\n server.setState(ServerState.ACTIVE);\n }\n @Override\n public void passivate(Server server) {\n server.setState(ServerState.IDLE);\n }\n public static void releasePort(Integer port) {\n logger.debug(\"Releasing port \" + port);\n portUsage.put(port, PortStatus.FREE);\n }\n public Integer getAvailablePort() {\n for (Map.Entry<Integer, PortStatus> entry : portUsage.entrySet()) {\n if (PortStatus.FREE == entry.getValue()) {\n // return available port\n logger.debug(\"Portusage \" + portUsage.toString());\n return entry.getKey();\n }\n }\n // if no port is free\n logger.debug(\"Nothing free in Portusage \" + portUsage.toString());\n return basePort + portUsage.size();\n }\n /*Getters and Setters*/\n public String getExec() {\n return exec;\n }\n public void setExec(String exec) {\n this.exec = exec;\n }\n public String getScript() {\n return script;\n }\n public void setScript(String script) {\n this.script = script;\n }\n public String getHost() {\n return host;\n }\n public void setHost(String host) {\n this.host = host;\n }\n public int getBasePort() {\n return basePort;\n }\n public void setBasePort(int basePort) {\n this.basePort = basePort;\n }\n public int getReadTimeout() {\n return readTimeout;\n }\n public void setReadTimeout(int readTimeout) {\n this.readTimeout = readTimeout;\n }\n public int getConnectTimeout() {\n return connectTimeout;\n }\n public void setConnectTimeout(int connectTimeout) {\n this.connectTimeout = connectTimeout;\n }\n public int getMaxTimeout() {\n return maxTimeout;\n }\n public void setMaxTimeout(int maxTimeout) {\n this.maxTimeout = maxTimeout;\n }\n @PostConstruct\n public void afterBeanInit() {\n String jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();\n try {\n jarLocation = URLDecoder.decode(jarLocation, \"utf-8\");\n // get filesystem depend path\n jarLocation = new File(jarLocation).getCanonicalPath();\n } catch (UnsupportedEncodingException ueex) {\n logger.error(ueex);\n } catch (IOException ioex) {\n logger.error(ioex);\n }\n try {\n JarFile jar = new JarFile(jarLocation);\n for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {\n JarEntry entry = entries.nextElement();\n String name = entry.getName();\n if (name.startsWith(\"phantomjs/\")) {\n File file = new File(tmpDir + name);\n if (name.endsWith(\"/\")) {\n file.mkdir();\n } else {\n InputStream in = jar.getInputStream(entry);\n IOUtils.copy(in, new FileOutputStream(file));\n }\n }\n }\n } catch (IOException ioex) {\n logger.error(ioex);\n }\n }\n}"}}},{"rowIdx":1292,"cells":{"answer":{"kind":"string","value":"package net.ttddyy.evernote.rest;\nimport org.junit.Test;\nimport static org.mockito.BDDMockito.given;\nimport static org.mockito.Mockito.verify;\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;\n/**\n * Miscellaneous tests for {@link StoreOperationController}.\n *\n * @author Tadaya Tsuyukubo\n */\npublic class StoreOperationControllerMiscIntegrationTest extends AbstractStoreOperationControllerIntegrationTest {\n @Test\n public void testNoInputForNoParameterMethod() throws Exception {\n given(userStoreOperations.isBusinessUser()).willReturn(true);\n mockMvc.perform(post(\"/userStore/isBusinessUser\"));\n verify(userStoreOperations).isBusinessUser();\n }\n}"}}},{"rowIdx":1293,"cells":{"answer":{"kind":"string","value":"package org.springframework.data.gclouddatastore.repository;\nimport static org.hamcrest.Matchers.contains;\nimport static org.hamcrest.Matchers.instanceOf;\nimport java.net.URI;\nimport java.nio.charset.Charset;\nimport java.time.Instant;\nimport java.time.LocalDateTime;\nimport java.time.OffsetDateTime;\nimport java.time.ZonedDateTime;\nimport java.time.ZoneId;\nimport java.util.Arrays;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.springframework.data.gclouddatastore.repository.Unmarshaller;\nimport org.springframework.data.annotation.Id;\nimport com.google.cloud.Timestamp;\nimport com.google.cloud.datastore.Blob;\nimport com.google.cloud.datastore.DoubleValue;\nimport com.google.cloud.datastore.Entity;\nimport com.google.cloud.datastore.Key;\nimport com.google.cloud.datastore.LongValue;\nimport com.google.cloud.datastore.StringValue;\npublic class UnmarshallerTest {\n @Data\n @NoArgsConstructor\n public static class TestBean {\n @Id\n long id;\n Object object;\n byte[] bytes;\n String string;\n Boolean boxedBoolean;\n boolean primitiveBoolean;\n Double boxedDouble;\n double primitiveDouble;\n Float boxedFloat;\n float primitiveFloat;\n Long boxedLong;\n long primitiveLong;\n Integer boxedInteger;\n int primitiveInt;\n Short boxedShort;\n short primitiveShort;\n Byte boxedByte;\n byte primitiveByte;\n List<?> list;\n LinkedList<?> linkedList;\n Map<String, Object> map;\n URI uri;\n Instant instant;\n Date date;\n Calendar calendar;\n java.sql.Timestamp sqlTimestamp;\n LocalDateTime localDateTime;\n OffsetDateTime offsetDateTime;\n ZonedDateTime zonedDateTime;\n }\n @Test\n public void testUnmarshalToObject_Blob() {\n //Setup\n byte[] hello = \"hello\".getBytes(Charset.forName(\"UTF-8\"));\n Key key = Key.newBuilder(\"project\", \"kind\", 1).build();\n Entity entity = Entity.newBuilder(key)\n .set(\"object\", Blob.copyFrom(hello))\n .set(\"bytes\", Blob.copyFrom(hello))\n .set(\"string\", Blob.copyFrom(hello))\n .build();\n Unmarshaller unmarshaller = new Unmarshaller();\n TestBean bean = new TestBean();\n // Exercise\n unmarshaller.unmarshalToObject(entity, bean);\n // Verify\n Assert.assertArrayEquals(hello, (byte[])bean.object);\n Assert.assertArrayEquals(hello, bean.bytes);\n Assert.assertEquals(\"hello\", bean.string);\n }\n @Test\n public void testUnmarshalToObject_Boolean() {\n //Setup\n Key key = Key.newBuilder(\"project\", \"kind\", 1).build();\n Entity entity = Entity.newBuilder(key)\n .set(\"object\", true)\n .set(\"boxedBoolean\", true)\n .set(\"primitiveBoolean\", true)\n .build();\n Unmarshaller unmarshaller = new Unmarshaller();\n TestBean bean = new TestBean();\n // Exercise\n unmarshaller.unmarshalToObject(entity, bean);\n // Verify\n Assert.assertEquals(Boolean.TRUE, bean.object);\n Assert.assertEquals(Boolean.TRUE, bean.boxedBoolean);\n Assert.assertTrue(bean.primitiveBoolean);\n }\n @Test\n public void testUnmarshalToObject_Double() {\n //Setup\n Key key = Key.newBuilder(\"project\", \"kind\", 1).build();\n Entity entity = Entity.newBuilder(key)\n .set(\"object\", 3.14)\n .set(\"boxedDouble\", 3.14)\n .set(\"primitiveDouble\", 3.14)\n .set(\"boxedFloat\", 3.14)\n .set(\"primitiveFloat\", 3.14)\n .set(\"boxedLong\", 3.14)\n .set(\"primitiveLong\", 3.14)\n .set(\"boxedInteger\", 3.14)\n .set(\"primitiveInt\", 3.14)\n .set(\"boxedShort\", 3.14)\n .set(\"primitiveShort\", 3.14)\n .set(\"boxedByte\", 3.14)\n .set(\"primitiveByte\", 3.14)\n .build();\n Unmarshaller unmarshaller = new Unmarshaller();\n TestBean bean = new TestBean();\n // Exercise\n unmarshaller.unmarshalToObject(entity, bean);\n // Verify\n Assert.assertEquals(Double.valueOf(3.14), bean.object);\n Assert.assertEquals(Double.valueOf(3.14), bean.boxedDouble);\n Assert.assertEquals(3.14, bean.primitiveDouble, 0.0);\n Assert.assertEquals(Float.valueOf(3.14f), bean.boxedFloat);\n Assert.assertEquals(3.14f, bean.primitiveFloat, 0.0f);\n Assert.assertEquals(Long.valueOf(3L), bean.boxedLong);\n Assert.assertEquals(3, bean.primitiveLong);\n Assert.assertEquals(Integer.valueOf(3), bean.boxedInteger);\n Assert.assertEquals(3, bean.primitiveInt);\n Assert.assertEquals(Short.valueOf((short)3), bean.boxedShort);\n Assert.assertEquals(3, bean.primitiveShort);\n Assert.assertEquals(Byte.valueOf((byte)3), bean.boxedByte);\n Assert.assertEquals(3, bean.primitiveByte);\n }\n @Test\n public void testUnmarshalToObject_Long() {\n //Setup\n Key key = Key.newBuilder(\"project\", \"kind\", 1).build();\n Entity entity = Entity.newBuilder(key)\n .set(\"object\", 42)\n .set(\"boxedLong\", 42)\n .set(\"primitiveLong\", 42)\n .set(\"boxedInteger\", 42)\n .set(\"primitiveInt\", 42)\n .set(\"boxedShort\", 42)\n .set(\"primitiveShort\", 42)\n .set(\"boxedByte\", 42)\n .set(\"primitiveByte\", 42)\n .set(\"boxedDouble\", 42)\n .set(\"primitiveDouble\", 42)\n .set(\"boxedFloat\", 42)\n .set(\"primitiveFloat\", 42)\n .build();\n Unmarshaller unmarshaller = new Unmarshaller();\n TestBean bean = new TestBean();\n // Exercise\n unmarshaller.unmarshalToObject(entity, bean);\n // Verify\n Assert.assertEquals(Long.valueOf(42), bean.object);\n Assert.assertEquals(Long.valueOf(42), bean.boxedLong);\n Assert.assertEquals(42L, bean.primitiveLong);\n Assert.assertEquals(Integer.valueOf(42), bean.boxedInteger);\n Assert.assertEquals(42, bean.primitiveInt);\n Assert.assertEquals(Short.valueOf((short)42), bean.boxedShort);\n Assert.assertEquals(42, bean.primitiveShort);\n Assert.assertEquals(Byte.valueOf((byte)42), bean.boxedByte);\n Assert.assertEquals(42, bean.primitiveByte);\n Assert.assertEquals(Double.valueOf(42.0), bean.boxedDouble);\n Assert.assertEquals(42.0, bean.primitiveDouble, 0.0);\n Assert.assertEquals(Float.valueOf(42.0f), bean.boxedFloat);\n Assert.assertEquals(42.0f, bean.primitiveFloat, 0.0f);\n }\n @Test\n public void testUnmarshalToObject_String() throws Exception {\n //Setup\n Key key = Key.newBuilder(\"project\", \"kind\", 1).build();\n Entity entity = Entity.newBuilder(key)\n .set(\"object\", \"hello\")\n .set(\"string\", \"hello\")\n .set(\"bytes\", \"hello\")\n .set(\"boxedLong\", \"42\")\n .set(\"primitiveLong\", \"42\")\n .set(\"boxedInteger\", \"42\")\n .set(\"primitiveInt\", \"42\")\n .set(\"boxedShort\", \"42\")\n .set(\"primitiveShort\", \"42\")\n .set(\"boxedByte\", \"42\")\n .set(\"primitiveByte\", \"42\")\n .set(\"boxedDouble\", \"3.14\")\n .set(\"primitiveDouble\", \"3.14\")\n .set(\"boxedFloat\", \"3.14\")\n .set(\"primitiveFloat\", \"3.14\")\n .set(\"uri\", \"https://example.com\")\n .build();\n Unmarshaller unmarshaller = new Unmarshaller();\n TestBean bean = new TestBean();\n // Exercise\n unmarshaller.unmarshalToObject(entity, bean);\n // Verify\n Assert.assertEquals(\"hello\", bean.object);\n Assert.assertEquals(\"hello\", bean.string);\n Assert.assertArrayEquals(\"hello\".getBytes(Charset.forName(\"UTF-8\")), bean.bytes);\n Assert.assertEquals(Long.valueOf(42), bean.boxedLong);\n Assert.assertEquals(42L, bean.primitiveLong);\n Assert.assertEquals(Integer.valueOf(42), bean.boxedInteger);\n Assert.assertEquals(42, bean.primitiveInt);\n Assert.assertEquals(Short.valueOf((short)42), bean.boxedShort);\n Assert.assertEquals(42, bean.primitiveShort);\n Assert.assertEquals(Byte.valueOf((byte)42), bean.boxedByte);\n Assert.assertEquals(42, bean.primitiveByte);\n Assert.assertEquals(Double.valueOf(3.14), bean.boxedDouble);\n Assert.assertEquals(3.14, bean.primitiveDouble, 0.0);\n Assert.assertEquals(Float.valueOf(3.14f), bean.boxedFloat);\n Assert.assertEquals(3.14f, bean.primitiveFloat, 0.0f);\n Assert.assertEquals(new URI(\"https://example.com\"), bean.uri);\n }\n @Test\n public void testUnmarshalToObject_List() {\n //Setup\n Key key = Key.newBuilder(\"project\", \"kind\", 1).build();\n Entity entity = Entity.newBuilder(key)\n .set(\"object\", Arrays.asList(DoubleValue.of(3.14), LongValue.of(42), StringValue.of(\"hello\")))\n .set(\"list\", Arrays.asList(DoubleValue.of(3.14), LongValue.of(42), StringValue.of(\"hello\")))\n .set(\"linkedList\", Arrays.asList(DoubleValue.of(3.14), LongValue.of(42), StringValue.of(\"hello\")))\n .build();\n Unmarshaller unmarshaller = new Unmarshaller();\n TestBean bean = new TestBean();\n bean.linkedList = new LinkedList<Object>();\n // Exercise\n unmarshaller.unmarshalToObject(entity, bean);\n // Verify\n Assert.assertThat((List<?>)bean.object, contains(3.14, 42L, \"hello\"));\n Assert.assertThat(bean.list, contains(3.14, 42L, \"hello\"));\n Assert.assertThat(bean.linkedList, contains(3.14, 42L, \"hello\"));\n Assert.assertThat(bean.linkedList, instanceOf(LinkedList.class));\n }\n @Test\n public void testUnmarshalToObject_Map1() {\n //Setup\n Key key = Key.newBuilder(\"project\", \"kind\", 1).build();\n Entity entity = Entity.newBuilder(key)\n .set(\"object\", Entity.newBuilder().set(\"k\", \"v\").build())\n .set(\"map\", Entity.newBuilder().set(\"k\", \"v\").build())\n .build();\n Unmarshaller unmarshaller = new Unmarshaller();\n TestBean bean = new TestBean();\n // Exercise\n unmarshaller.unmarshalToObject(entity, bean);\n // Verify\n Map<String, Object> expected = new HashMap<>();\n expected.put(\"k\", \"v\");\n Assert.assertEquals(expected, bean.object);\n Assert.assertEquals(expected, bean.map);\n }\n @Test\n public void testUnmarshalToObject_Map2() {\n //Setup\n Key key = Key.newBuilder(\"project\", \"kind\", 1).build();\n Entity entity = Entity.newBuilder(key)\n .set(\"object\", Entity.newBuilder().set(\"k1\",\n Entity.newBuilder().set(\"k2\", \"v2\").build()).build())\n .set(\"map\", Entity.newBuilder().set(\"k1\",\n Entity.newBuilder().set(\"k2\", \"v2\").build()).build())\n .build();\n Unmarshaller unmarshaller = new Unmarshaller();\n TestBean bean = new TestBean();\n // Exercise\n unmarshaller.unmarshalToObject(entity, bean);\n // Verify\n Map<String, Object> innerMap = new HashMap<>();\n innerMap.put(\"k2\", \"v2\");\n Map<String, Object> expected = new HashMap<>();\n expected.put(\"k1\", innerMap);\n Assert.assertEquals(expected, bean.object);\n Assert.assertEquals(expected, bean.map);\n }\n @Test\n public void testUnmarshalToObject_Timestamp() {\n //Setup\n Key key = Key.newBuilder(\"project\", \"kind\", 1).build();\n Entity entity = Entity.newBuilder(key)\n .set(\"object\", Timestamp.parseTimestamp(\"2017-07-09T12:34:56Z\"))\n .set(\"primitiveLong\", Timestamp.parseTimestamp(\"2017-07-09T12:34:56Z\"))\n .set(\"boxedLong\", Timestamp.parseTimestamp(\"2017-07-09T12:34:56Z\"))\n .set(\"date\", Timestamp.parseTimestamp(\"2017-07-09T12:34:56Z\"))\n .set(\"calendar\", Timestamp.parseTimestamp(\"2017-07-09T12:34:56Z\"))\n .set(\"sqlTimestamp\", Timestamp.parseTimestamp(\"2017-07-09T12:34:56Z\"))\n .set(\"localDateTime\", Timestamp.parseTimestamp(\"2017-07-09T12:34:56Z\"))\n .set(\"offsetDateTime\", Timestamp.parseTimestamp(\"2017-07-09T12:34:56Z\"))\n .set(\"zonedDateTime\", Timestamp.parseTimestamp(\"2017-07-09T12:34:56Z\"))\n .build();\n Unmarshaller unmarshaller = new Unmarshaller();\n TestBean bean = new TestBean();\n // Exercise\n unmarshaller.unmarshalToObject(entity, bean);\n // Verify\n Assert.assertEquals(\n OffsetDateTime.parse(\"2017-07-09T12:34:56Z\").toInstant(),\n (Instant)bean.object);\n Assert.assertEquals(\n OffsetDateTime.parse(\"2017-07-09T12:34:56Z\").toEpochSecond(),\n bean.primitiveLong);\n Assert.assertEquals(\n Long.valueOf(OffsetDateTime.parse(\"2017-07-09T12:34:56Z\").toEpochSecond()),\n bean.boxedLong);\n Assert.assertEquals(\n Date.from(OffsetDateTime.parse(\"2017-07-09T12:34:56Z\").toInstant()),\n bean.date);\n Assert.assertEquals(\n new Calendar.Builder()\n .setInstant(Date.from(OffsetDateTime.parse(\"2017-07-09T12:34:56Z\").toInstant()))\n .build(),\n bean.calendar);\n Assert.assertEquals(\n java.sql.Timestamp.from(OffsetDateTime.parse(\"2017-07-09T12:34:56Z\").toInstant()),\n bean.sqlTimestamp);\n Assert.assertEquals(\n OffsetDateTime.parse(\"2017-07-09T12:34:56Z\")\n .atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime(),\n bean.localDateTime);\n Assert.assertEquals(\n OffsetDateTime.parse(\"2017-07-09T12:34:56Z\"),\n bean.offsetDateTime);\n Assert.assertEquals(\n ZonedDateTime.parse(\"2017-07-09T12:34:56Z\"),\n bean.zonedDateTime);\n }\n}"}}},{"rowIdx":1294,"cells":{"answer":{"kind":"string","value":"package com.github.davidmoten.fsm.runtime.rx;\nimport java.util.ArrayDeque;\nimport java.util.Deque;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.TimeUnit;\nimport com.github.davidmoten.fsm.runtime.CancelTimedSignal;\nimport com.github.davidmoten.fsm.runtime.Clock;\nimport com.github.davidmoten.fsm.runtime.EntityBehaviour;\nimport com.github.davidmoten.fsm.runtime.EntityStateMachine;\nimport com.github.davidmoten.fsm.runtime.Event;\nimport com.github.davidmoten.fsm.runtime.ObjectState;\nimport com.github.davidmoten.fsm.runtime.Search;\nimport com.github.davidmoten.fsm.runtime.Signal;\nimport com.github.davidmoten.guavamini.Preconditions;\nimport com.github.davidmoten.rx.Transformers;\nimport rx.Observable;\nimport rx.Observable.Transformer;\nimport rx.Observer;\nimport rx.Scheduler;\nimport rx.Scheduler.Worker;\nimport rx.Subscription;\nimport rx.functions.Action1;\nimport rx.functions.Func1;\nimport rx.observables.GroupedObservable;\nimport rx.observables.SyncOnSubscribe;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\npublic final class Processor<Id> {\n private final Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory;\n private final PublishSubject<Signal<?, Id>> subject;\n private final Scheduler signalScheduler;\n private final Scheduler processingScheduler;\n private final Map<ClassId<?, Id>, EntityStateMachine<?, Id>> stateMachines = new ConcurrentHashMap<>();\n private final Map<ClassIdPair<Id>, Subscription> subscriptions = new ConcurrentHashMap<>();\n private final Observable<Signal<?, Id>> signals;\n private final Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform;\n private final Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy;\n private final Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory; // nullable\n private final Clock signallerClock;\n private final Search<Id> search = new Search<Id>() {\n @Override\n public <T> Optional<T> search(Class<T> cls, Id id) {\n return getStateMachine(cls, id).get();\n }\n };\n private Processor(Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory,\n Scheduler processingScheduler, Scheduler signalScheduler,\n Observable<Signal<?, Id>> signals,\n Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform,\n Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy,\n Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory) {\n Preconditions.checkNotNull(behaviourFactory);\n Preconditions.checkNotNull(signalScheduler);\n Preconditions.checkNotNull(signals);\n Preconditions.checkNotNull(entityTransform);\n Preconditions.checkNotNull(preGroupBy);\n // mapFactory is nullable\n this.behaviourFactory = behaviourFactory;\n this.signalScheduler = signalScheduler;\n this.processingScheduler = processingScheduler;\n this.subject = PublishSubject.create();\n this.signals = signals;\n this.entityTransform = entityTransform;\n this.preGroupBy = preGroupBy;\n this.mapFactory = mapFactory;\n this.signallerClock = Clock.from(signalScheduler);\n }\n public static <Id> Builder<Id> behaviourFactory(\n Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory) {\n return new Builder<Id>().behaviourFactory(behaviourFactory);\n }\n public static <T, Id> Builder<Id> behaviour(Class<T> cls, EntityBehaviour<T, Id> behaviour) {\n return new Builder<Id>().behaviour(cls, behaviour);\n }\n public static <Id> Builder<Id> signalScheduler(Scheduler signalScheduler) {\n return new Builder<Id>().signalScheduler(signalScheduler);\n }\n public static <Id> Builder<Id> processingScheduler(Scheduler processingScheduler) {\n return new Builder<Id>().processingScheduler(processingScheduler);\n }\n public static class Builder<Id> {\n private Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory;\n private Scheduler signalScheduler = Schedulers.computation();\n private Scheduler processingScheduler = Schedulers.immediate();\n private Observable<Signal<?, Id>> signals = Observable.empty();\n private Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform = g -> g;\n private Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy = x -> x;\n private Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory; // nullable\n private final Map<Class<?>, EntityBehaviour<?, Id>> behaviours = new HashMap<>();\n private Builder() {\n }\n public <T> Builder<Id> behaviour(Class<T> cls, EntityBehaviour<T, Id> behaviour) {\n behaviours.put(cls, behaviour);\n return this;\n }\n public Builder<Id> behaviourFactory(\n Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory) {\n this.behaviourFactory = behaviourFactory;\n return this;\n }\n public Builder<Id> signalScheduler(Scheduler signalScheduler) {\n this.signalScheduler = signalScheduler;\n return this;\n }\n public Builder<Id> processingScheduler(Scheduler processingScheduler) {\n this.processingScheduler = processingScheduler;\n return this;\n }\n public Builder<Id> signals(Observable<Signal<?, Id>> signals) {\n this.signals = signals;\n return this;\n }\n public Builder<Id> entityTransform(\n Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform) {\n this.entityTransform = entityTransform;\n return this;\n }\n public Builder<Id> preGroupBy(Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy) {\n this.preGroupBy = preGroupBy;\n return this;\n }\n public Builder<Id> mapFactory(\n Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory) {\n this.mapFactory = mapFactory;\n return this;\n }\n public Processor<Id> build() {\n Preconditions.checkArgument(behaviourFactory != null || !behaviours.isEmpty(),\n \"one of behaviourFactory or multiple calls to behaviour must be made (behaviour must be specified)\");\n Preconditions.checkArgument(behaviourFactory == null || behaviours.isEmpty(),\n \"cannot specify both behaviourFactory and behaviour\");\n if (!behaviours.isEmpty()) {\n behaviourFactory = cls -> behaviours.get(cls);\n }\n return new Processor<Id>(behaviourFactory, processingScheduler, signalScheduler,\n signals, entityTransform, preGroupBy, mapFactory);\n }\n }\n public Observable<EntityStateMachine<?, Id>> observable() {\n return Observable.defer(() -> {\n Worker worker = signalScheduler.createWorker();\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n Observable<GroupedObservable<ClassId<?, Id>, Signal<?, Id>>> o1 = subject\n .toSerialized()\n .onBackpressureBuffer()\n .mergeWith(signals)\n .doOnUnsubscribe(() -> worker.unsubscribe())\n .compose(preGroupBy)\n .compose(Transformers\n .<Signal<?, Id>, ClassId<?, Id>, Signal<?, Id>> groupByEvicting(\n signal -> new ClassId(signal.cls(), signal.id()), x -> x,\n mapFactory));\n return o1.flatMap(g -> {\n Observable<EntityStateMachine<?, Id>> obs = g\n .flatMap(processLambda(worker, g))\n .doOnNext(m -> stateMachines.put(g.getKey(), m))\n .subscribeOn(processingScheduler);\n return entityTransform.call(GroupedObservable.from(g.getKey(), obs));\n });\n });\n }\n private Func1<? super Signal<?, Id>, Observable<EntityStateMachine<?, Id>>> processLambda(\n Worker worker, GroupedObservable<ClassId<?, Id>, Signal<?, Id>> g) {\n return x -> process(g.getKey(), x.event(), worker);\n }\n private static final class Signals<Id> {\n final Deque<Event<?>> signalsToSelf = new ArrayDeque<>();\n final Deque<Signal<?, Id>> signalsToOther = new ArrayDeque<>();\n }\n private Observable<EntityStateMachine<?, Id>> process(ClassId<?, Id> cid, Event<?> x,\n Worker worker) {\n return Observable.create(new SyncOnSubscribe<Signals<Id>, EntityStateMachine<?, Id>>() {\n @Override\n protected Signals<Id> generateState() {\n Signals<Id> signals = new Signals<>();\n signals.signalsToSelf.offerFirst(x);\n return signals;\n }\n @Override\n protected Signals<Id> next(Signals<Id> signals,\n Observer<? super EntityStateMachine<?, Id>> observer) {\n @SuppressWarnings(\"unchecked\")\n EntityStateMachine<Object, Id> m = (EntityStateMachine<Object, Id>) getStateMachine(\n cid.cls(), cid.id());\n @SuppressWarnings(\"unchecked\")\n Event<Object> event = (Event<Object>) signals.signalsToSelf.pollLast();\n if (event != null) {\n applySignalToSelf(signals, observer, m, event);\n } else {\n applySignalsToOthers(cid, worker, signals);\n observer.onCompleted();\n }\n return signals;\n }\n @SuppressWarnings(\"unchecked\")\n private <T> void applySignalToSelf(Signals<Id> signals,\n Observer<? super EntityStateMachine<?, Id>> observer,\n EntityStateMachine<T, Id> m, Event<T> event) {\n m = m.signal(event);\n // stateMachines.put(id, m);\n observer.onNext(m);\n List<Event<? super T>> list = m.signalsToSelf();\n for (int i = list.size() - 1; i >= 0; i\n signals.signalsToSelf.offerLast(list.get(i));\n }\n for (Signal<?, ?> signal : m.signalsToOther()) {\n signals.signalsToOther.offerFirst((Signal<?, Id>) signal);\n }\n }\n private void applySignalsToOthers(ClassId<?, Id> cid, Worker worker,\n Signals<Id> signals) {\n Signal<?, Id> signal;\n while ((signal = signals.signalsToOther.pollLast()) != null) {\n Signal<?, Id> s = signal;\n if (signal.isImmediate()) {\n subject.onNext(signal);\n } else if (signal.event() instanceof CancelTimedSignal) {\n cancel(signal);\n } else {\n long delayMs = signal.time().get() - worker.now();\n if (delayMs <= 0) {\n subject.onNext(signal);\n } else {\n scheduleSignal(cid, worker, signal, s, delayMs);\n }\n }\n }\n }\n private void cancel(Signal<?, Id> signal) {\n @SuppressWarnings(\"unchecked\")\n CancelTimedSignal<Id> s = ((CancelTimedSignal<Id>) signal.event());\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n Subscription sub = subscriptions\n .remove(new ClassIdPair<Id>(new ClassId(s.fromClass(), s.fromId()),\n new ClassId(signal.cls(), signal.id())));\n if (sub != null) {\n sub.unsubscribe();\n }\n }\n private void scheduleSignal(ClassId<?, Id> from, Worker worker, Signal<?, Id> signal,\n Signal<?, Id> s, long delayMs) {\n // record pairwise signal so we can cancel it if\n // desired\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n ClassIdPair<Id> idPair = new ClassIdPair<Id>(from,\n new ClassId(signal.cls(), signal.id()));\n long t1 = signalScheduler.now();\n Subscription subscription = worker.schedule(() -> {\n subject.onNext(s.now());\n } , delayMs, TimeUnit.MILLISECONDS);\n long t2 = signalScheduler.now();\n worker.schedule(() -> {\n subscriptions.remove(idPair);\n } , delayMs - (t2 - t1), TimeUnit.MILLISECONDS);\n Subscription previous = subscriptions.put(idPair, subscription);\n if (previous != null) {\n previous.unsubscribe();\n }\n }\n });\n }\n @SuppressWarnings(\"unchecked\")\n private <T> EntityStateMachine<T, Id> getStateMachine(Class<T> cls, Id id) {\n return (EntityStateMachine<T, Id>) stateMachines\n .computeIfAbsent(new ClassId<T, Id>(cls, id),\n clsId -> (EntityStateMachine<T, Id>) behaviourFactory.call(cls)\n .create(id)\n .withSearch(search)\n .withClock(signallerClock));\n }\n public <T> Optional<T> getObject(Class<T> cls, Id id) {\n return getStateMachine(cls, id).get();\n }\n public void signal(Signal<?, Id> signal) {\n subject.onNext(signal);\n }\n public <T> void signal(Class<T> cls, Id id, Event<? super T> event) {\n subject.onNext(Signal.create(cls, id, event));\n }\n public <T> void signal(ClassId<T, Id> cid, Event<? super T> event) {\n signal(cid.cls(), cid.id(), event);\n }\n @SuppressWarnings(\"unchecked\")\n public <T> ObjectState<T> get(Class<T> cls, Id id) {\n return (EntityStateMachine<T, Id>) stateMachines.get(new ClassId<T, Id>(cls, id));\n }\n public void onCompleted() {\n subject.onCompleted();\n }\n public void cancelSignal(Class<?> fromClass, Id fromId, Class<?> toClass, Id toId) {\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n Subscription subscription = subscriptions.remove(\n new ClassIdPair<Id>(new ClassId(fromClass, fromId), new ClassId(toClass, toId)));\n if (subscription != null) {\n subscription.unsubscribe();\n }\n }\n public void cancelSignalToSelf(Class<?> cls, Id id) {\n cancelSignal(cls, id, cls, id);\n }\n public void cancelSignalToSelf(ClassId<?, Id> cid) {\n cancelSignalToSelf(cid.cls(), cid.id());\n }\n}"}}},{"rowIdx":1295,"cells":{"answer":{"kind":"string","value":"package com.github.davidmoten.fsm.runtime.rx;\nimport java.util.ArrayDeque;\nimport java.util.Deque;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.TimeUnit;\nimport com.github.davidmoten.fsm.runtime.CancelTimedSignal;\nimport com.github.davidmoten.fsm.runtime.EntityStateMachine;\nimport com.github.davidmoten.fsm.runtime.Event;\nimport com.github.davidmoten.fsm.runtime.ObjectState;\nimport com.github.davidmoten.fsm.runtime.Signal;\nimport com.github.davidmoten.guavamini.Preconditions;\nimport rx.Observable;\nimport rx.Observer;\nimport rx.Scheduler;\nimport rx.Scheduler.Worker;\nimport rx.Subscription;\nimport rx.functions.Func2;\nimport rx.observables.SyncOnSubscribe;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\npublic final class Processor<Id> {\n private final Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory;\n private final PublishSubject<Signal<?, Id, ?>> subject;\n private final Scheduler signalScheduler;\n private final Scheduler processingScheduler;\n private final Map<ClassId<?>, EntityStateMachine<?>> stateMachines = new ConcurrentHashMap<>();\n private final Map<ClassIdPair<Id>, Subscription> subscriptions = new ConcurrentHashMap<>();\n private Processor(Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory,\n Scheduler processingScheduler, Scheduler signalScheduler) {\n Preconditions.checkNotNull(stateMachineFactory);\n Preconditions.checkNotNull(signalScheduler);\n this.stateMachineFactory = stateMachineFactory;\n this.signalScheduler = signalScheduler;\n this.processingScheduler = processingScheduler;\n this.subject = PublishSubject.create();\n }\n public static <Id> Builder<Id> stateMachineFactory(\n Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory) {\n return new Builder<Id>().stateMachineFactory(stateMachineFactory);\n }\n public static <Id> Builder<Id> signalScheduler(Scheduler signalScheduler) {\n return new Builder<Id>().signalScheduler(signalScheduler);\n }\n public static <Id> Builder<Id> processingScheduler(Scheduler processingScheduler) {\n return new Builder<Id>().processingScheduler(processingScheduler);\n }\n public static class Builder<Id> {\n private Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory;\n private Scheduler signalScheduler = Schedulers.computation();\n private Scheduler processingScheduler = Schedulers.immediate();\n private Builder() {\n }\n public Builder<Id> stateMachineFactory(\n Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory) {\n this.stateMachineFactory = stateMachineFactory;\n return this;\n }\n public Builder<Id> signalScheduler(Scheduler signalScheduler) {\n this.signalScheduler = signalScheduler;\n return this;\n }\n public Builder<Id> processingScheduler(Scheduler processingScheduler) {\n this.processingScheduler = processingScheduler;\n return this;\n }\n public Processor<Id> build() {\n return new Processor<Id>(stateMachineFactory, processingScheduler, signalScheduler);\n }\n }\n public Observable<EntityStateMachine<?>> observable() {\n return Observable.defer(() -> {\n Worker worker = signalScheduler.createWorker();\n return subject\n .toSerialized()\n .doOnUnsubscribe(() -> worker.unsubscribe())\n .groupBy(signal -> new ClassId<Id>(signal.cls(), signal.id()))\n .flatMap(g -> g\n .flatMap(x -> process(g.getKey(), x.event(), worker))\n .doOnNext(m -> stateMachines.put(g.getKey(), m))\n .subscribeOn(processingScheduler));\n });\n }\n private static final class Signals<Id> {\n final Deque<Event<?>> signalsToSelf = new ArrayDeque<>();\n final Deque<Signal<?, Id, ?>> signalsToOther = new ArrayDeque<>();\n }\n private Observable<EntityStateMachine<?>> process(ClassId<Id> cid, Event<?> x, Worker worker) {\n return Observable.create(new SyncOnSubscribe<Signals<Id>, EntityStateMachine<?>>() {\n @Override\n protected Signals<Id> generateState() {\n Signals<Id> signals = new Signals<>();\n signals.signalsToSelf.offerFirst(x);\n return signals;\n }\n @Override\n protected Signals<Id> next(Signals<Id> signals,\n Observer<? super EntityStateMachine<?>> observer) {\n EntityStateMachine<?> m = getStateMachine(cid.cls(), cid.id());\n Event<?> event = signals.signalsToSelf.pollLast();\n if (event != null) {\n applySignalToSelf(signals, observer, m, event);\n } else {\n applySignalsToOthers(cid, worker, signals);\n observer.onCompleted();\n }\n return signals;\n }\n @SuppressWarnings(\"unchecked\")\n private void applySignalToSelf(Signals<Id> signals,\n Observer<? super EntityStateMachine<?>> observer, EntityStateMachine<?> m,\n Event<?> event) {\n m = m.signal(event);\n // stateMachines.put(id, m);\n observer.onNext(m);\n List<Event<?>> list = m.signalsToSelf();\n for (int i = list.size() - 1; i >= 0; i\n signals.signalsToSelf.offerLast(list.get(i));\n }\n for (Signal<?, ?, ?> signal : m.signalsToOther()) {\n signals.signalsToOther.offerFirst((Signal<?, Id, ?>) signal);\n }\n }\n private void applySignalsToOthers(ClassId<Id> cid, Worker worker, Signals<Id> signals) {\n Signal<?, Id, ?> signal;\n while ((signal = signals.signalsToOther.pollLast()) != null) {\n Signal<?, Id, ?> s = signal;\n if (signal.isImmediate()) {\n subject.onNext(signal);\n } else if (signal.event() instanceof CancelTimedSignal) {\n cancel(signal);\n } else {\n long delayMs = signal.time() - worker.now();\n if (delayMs <= 0) {\n subject.onNext(signal);\n } else {\n scheduleSignal(cid, worker, signal, s, delayMs);\n }\n }\n }\n }\n private void cancel(Signal<?, Id, ?> signal) {\n @SuppressWarnings(\"unchecked\")\n CancelTimedSignal<Id> s = ((CancelTimedSignal<Id>) signal.event());\n Subscription sub = subscriptions\n .remove(new ClassIdPair<Id>(new ClassId<Id>(s.fromClass(), s.fromId()),\n new ClassId<Id>(signal.cls(), signal.id())));\n if (sub != null) {\n sub.unsubscribe();\n }\n }\n private void scheduleSignal(ClassId<Id> from, Worker worker, Signal<?, Id, ?> signal,\n Signal<?, Id, ?> s, long delayMs) {\n // record pairwise signal so we can cancel it if\n // desired\n ClassIdPair<Id> idPair = new ClassIdPair<Id>(from,\n new ClassId<Id>(signal.cls(), signal.id()));\n long t1 = signalScheduler.now();\n Subscription subscription = worker.schedule(() -> {\n subject.onNext(s.now());\n } , delayMs, TimeUnit.MILLISECONDS);\n long t2 = signalScheduler.now();\n worker.schedule(() -> {\n subscriptions.remove(idPair);\n } , delayMs - (t2 - t1), TimeUnit.MILLISECONDS);\n Subscription previous = subscriptions.put(idPair, subscription);\n if (previous != null) {\n previous.unsubscribe();\n }\n }\n });\n }\n @SuppressWarnings(\"unchecked\")\n private <T> EntityStateMachine<T> getStateMachine(Class<T> cls, Id id) {\n EntityStateMachine<T> m = (EntityStateMachine<T>) stateMachines\n .get(new ClassId<Id>(cls, id));\n if (m == null) {\n m = (EntityStateMachine<T>) stateMachineFactory.call(cls, id);\n }\n return m;\n }\n public <T> Optional<T> getObject(Class<T> cls, Id id) {\n return getStateMachine(cls, id).get();\n }\n public void signal(Signal<?, Id, ?> signal) {\n subject.onNext(signal);\n }\n public <T, R> void signal(Class<T> cls, Id id, Event<R> event) {\n subject.onNext(Signal.create(cls, id, event));\n }\n public <T> void signal(ClassId<Id> cid, Event<T> event) {\n subject.onNext(Signal.create(cid.cls(), cid.id(), event));\n }\n @SuppressWarnings(\"unchecked\")\n public <T> ObjectState<T> get(Class<T> cls, Id id) {\n return (EntityStateMachine<T>) stateMachines.get(new ClassId<Id>(cls, id));\n }\n public void onCompleted() {\n subject.onCompleted();\n }\n public void cancelSignal(Class<?> fromClass, Id fromId, Class<?> toClass, Id toId) {\n Subscription subscription = subscriptions.remove(new ClassIdPair<Id>(\n new ClassId<Id>(fromClass, fromId), new ClassId<Id>(toClass, toId)));\n if (subscription != null) {\n subscription.unsubscribe();\n }\n }\n public void cancelSignalToSelf(Class<?> cls, Id id) {\n cancelSignal(cls, id, cls, id);\n }\n public void cancelSignalToSelf(ClassId<Id> cid) {\n cancelSignalToSelf(cid.cls(), cid.id());\n }\n}"}}},{"rowIdx":1296,"cells":{"answer":{"kind":"string","value":"package com.emc.mongoose.storage.mock.impl.base;\nimport com.emc.mongoose.common.collection.ListingLRUMap;\nimport com.emc.mongoose.common.concurrent.BlockingQueueTaskSequencer;\nimport com.emc.mongoose.common.concurrent.FutureTaskBase;\nimport com.emc.mongoose.model.api.data.ContentSource;\nimport com.emc.mongoose.model.impl.item.CsvFileItemInput;\nimport com.emc.mongoose.storage.mock.api.MutableDataItemMock;\nimport com.emc.mongoose.storage.mock.api.ObjectContainerMock;\nimport com.emc.mongoose.storage.mock.api.StorageIoStats;\nimport com.emc.mongoose.storage.mock.api.StorageMock;\nimport com.emc.mongoose.storage.mock.api.exception.ContainerMockException;\nimport com.emc.mongoose.storage.mock.api.exception.ContainerMockNotFoundException;\nimport com.emc.mongoose.storage.mock.api.exception.ObjectMockNotFoundException;\nimport com.emc.mongoose.storage.mock.api.exception.StorageMockCapacityLimitReachedException;\nimport com.emc.mongoose.ui.config.Config;\nimport com.emc.mongoose.ui.log.LogUtil;\nimport com.emc.mongoose.ui.log.Markers;\nimport org.apache.logging.log4j.Level;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport java.io.EOFException;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicLong;\npublic abstract class StorageMockBase<T extends MutableDataItemMock>\nimplements StorageMock<T> {\n private static final Logger LOG = LogManager.getLogger();\n private final AtomicBoolean started = new AtomicBoolean(false);\n private final String dataSrcPath;\n private final StorageIoStats ioStats;\n protected final ContentSource contentSrc;\n private final int storageCapacity, containerCapacity;\n private final ListingLRUMap<String, ObjectContainerMock<T>> storageMap;\n private final ObjectContainerMock<T> defaultContainer;\n private volatile boolean isCapacityExhausted = false;\n @SuppressWarnings(\"unchecked\")\n public StorageMockBase(\n final Config.StorageConfig.MockConfig mockConfig,\n final Config.LoadConfig.MetricsConfig metricsConfig,\n final Config.ItemConfig itemConfig,\n final ContentSource contentSrc\n ) {\n super();\n final Config.StorageConfig.MockConfig.ContainerConfig\n containerConfig = mockConfig.getContainerConfig();\n storageMap = new ListingLRUMap<>(containerConfig.getCountLimit());\n this.dataSrcPath = itemConfig.getInputConfig().getFile();\n this.contentSrc = contentSrc;\n this.ioStats = new BasicStorageIoStats(this, (int) metricsConfig.getPeriod());\n this.storageCapacity = mockConfig.getCapacity();\n this.containerCapacity = containerConfig.getCapacity();\n this.defaultContainer = new BasicObjectContainerMock<>(containerCapacity);\n storageMap.put(getClass().getSimpleName().toLowerCase(), defaultContainer);\n }\n // Container methods\n @Override\n public final void createContainer(final String name) {\n synchronized(storageMap) {\n storageMap.put(name, new BasicObjectContainerMock<>(containerCapacity));\n ioStats.containerCreate();\n }\n }\n @Override\n public final ObjectContainerMock<T> getContainer(final String name) {\n synchronized(storageMap) {\n return storageMap.get(name);\n }\n }\n @Override\n public final void deleteContainer(final String name) {\n synchronized(storageMap) {\n storageMap.remove(name);\n ioStats.containerDelete();\n }\n }\n // Object methods\n protected abstract T newDataObject(final String id, final long offset, final long size);\n @Override\n public final void createObject(\n final String containerName, final String id, final long offset, final long size\n ) throws ContainerMockNotFoundException, StorageMockCapacityLimitReachedException {\n if(isCapacityExhausted) {\n throw new StorageMockCapacityLimitReachedException();\n }\n final ObjectContainerMock<T> c = getContainer(containerName);\n if(c != null) {\n c.put(id, newDataObject(id, offset, size));\n } else {\n throw new ContainerMockNotFoundException(containerName);\n }\n }\n @Override\n public final void updateObject(\n final String containerName, final String id, final long offset, final long size\n ) throws ContainerMockException, ObjectMockNotFoundException {\n final ObjectContainerMock<T> c = getContainer(containerName);\n if(c != null) {\n final T obj = c.get(id);\n if(obj != null) {\n obj.update(offset, size);\n } else {\n throw new ObjectMockNotFoundException(id);\n }\n } else {\n throw new ContainerMockNotFoundException(containerName);\n }\n }\n @Override\n public final void appendObject(\n final String containerName, final String id, final long offset, final long size\n ) throws ContainerMockException, ObjectMockNotFoundException {\n final ObjectContainerMock<T> c = getContainer(containerName);\n if(c != null) {\n final T obj = c.get(id);\n if(obj != null) {\n obj.append(offset, size);\n } else {\n throw new ObjectMockNotFoundException(id);\n }\n } else {\n throw new ContainerMockNotFoundException(containerName);\n }\n }\n @Override\n public final T getObject(\n final String containerName, final String id, final long offset, final long size\n ) throws ContainerMockException {\n // TODO partial read using offset and size args\n final ObjectContainerMock<T> c = getContainer(containerName);\n if(c != null) {\n return c.get(id);\n } else {\n throw new ContainerMockNotFoundException(containerName);\n }\n }\n @Override\n public final void deleteObject(\n final String containerName, final String id, final long offset, final long size\n ) throws ContainerMockNotFoundException {\n final ObjectContainerMock<T> c = getContainer(containerName);\n if(c != null) {\n c.remove(id);\n } else {\n throw new ContainerMockNotFoundException(containerName);\n }\n }\n @Override\n public final T listObjects(\n final String containerName, final String afterObjectId, final Collection<T> outputBuffer,\n final int limit\n ) throws ContainerMockException {\n final ObjectContainerMock<T> container = getContainer(containerName);\n if(container != null) {\n return container.list(afterObjectId, outputBuffer, limit);\n } else {\n throw new ContainerMockNotFoundException(containerName);\n }\n }\n private final Thread storageCapacityMonitorThread = new Thread(\"storageMockCapacityMonitor\") {\n {\n setDaemon(true);\n }\n @SuppressWarnings(\"InfiniteLoopStatement\")\n @Override\n public final void run() {\n long currObjCount;\n try {\n while(true) {\n TimeUnit.SECONDS.sleep(1);\n currObjCount = getSize();\n if(!isCapacityExhausted && currObjCount > storageCapacity) {\n isCapacityExhausted = true;\n } else if(isCapacityExhausted && currObjCount <= storageCapacity) {\n isCapacityExhausted = false;\n }\n }\n } catch(final InterruptedException ignored) {\n }\n }\n };\n @Override\n public final void start() {\n loadPersistedDataItems();\n ioStats.start();\n doStart();\n storageCapacityMonitorThread.start();\n started.set(true);\n }\n @Override\n public final boolean isStarted() {\n return started.get();\n }\n protected abstract void doStart();\n @Override\n public long getSize() {\n long size = 0;\n synchronized(storageMap) {\n for(final ObjectContainerMock<T> container : storageMap.values()) {\n size += container.size();\n }\n }\n return size;\n }\n @Override\n public long getCapacity() {\n return storageCapacity;\n }\n @Override\n public final void putIntoDefaultContainer(final List<T> dataItems) {\n for(final T object : dataItems) {\n defaultContainer.put(object.getName(), object);\n }\n }\n @Override\n public StorageIoStats getStats() {\n return ioStats;\n }\n @SuppressWarnings({\"InfiniteLoopStatement\", \"unchecked\"})\n private void loadPersistedDataItems() {\n if(dataSrcPath != null && !dataSrcPath.isEmpty()) {\n final Path dataFilePath = Paths.get(dataSrcPath);\n if(!Files.exists(dataFilePath)) {\n LOG.warn(\n Markers.ERR, \"Data item source file @ \\\"\" + dataSrcPath + \"\\\" doesn't exists\"\n );\n return;\n }\n if(Files.isDirectory(dataFilePath)) {\n LOG.warn(\n Markers.ERR, \"Data item source file @ \\\"\" + dataSrcPath + \"\\\" is a directory\"\n );\n return;\n }\n if(Files.isReadable(dataFilePath)) {\n LOG.debug(\n Markers.ERR, \"Data item source file @ \\\"\" + dataSrcPath + \"\\\" is not readable\"\n );\n }\n final AtomicLong count = new AtomicLong(0);\n List<T> buff;\n int n;\n final Thread displayProgressThread = new Thread(() -> {\n try {\n while(true) {\n LOG.info(Markers.MSG, \"{} items loaded...\", count.get());\n TimeUnit.SECONDS.sleep(10);\n }\n } catch(final InterruptedException ignored) {\n }\n });\n try(\n final CsvFileItemInput<T>\n csvFileItemInput = new CsvFileItemInput<>(\n dataFilePath, (Class<T>) BasicMutableDataItemMock.class, contentSrc\n )\n ) {\n displayProgressThread.start();\n do {\n buff = new ArrayList<>(4096);\n n = csvFileItemInput.get(buff, 4096);\n if(n > 0) {\n putIntoDefaultContainer(buff);\n count.addAndGet(n);\n } else {\n break;\n }\n } while(true);\n } catch(final EOFException e) {\n LOG.info(Markers.MSG, \"Loaded {} data items from file {}\", count, dataFilePath);\n } catch(final IOException | NoSuchMethodException e) {\n LogUtil.exception(\n LOG, Level.WARN, e, \"Failed to load the data items from file \\\"{}\\\"\",\n dataFilePath\n );\n } finally {\n displayProgressThread.interrupt();\n }\n }\n }\n private abstract class ContainerTaskBase\n extends FutureTaskBase<T> {\n private final String containerName;\n public ContainerTaskBase(final String containerName) {\n this.containerName = containerName;\n }\n public ObjectContainerMock<T> getContainer() {\n return storageMap.get(containerName);\n }\n protected final boolean setException() {\n return setException(\n new ContainerMockNotFoundException(containerName)\n );\n }\n }\n private final class PutObjectsBatchTask\n extends FutureTaskBase<List<T>> {\n private final String containerName;\n private final List<T> objects;\n public PutObjectsBatchTask(final String containerName, final List<T> objects) {\n this.containerName = containerName;\n this.objects = objects;\n }\n @Override\n public final void run() {\n final ObjectContainerMock<T> container = storageMap.get(containerName);\n if(container != null) {\n objects.forEach(object -> container.put(object.getName(), object));\n set(new ArrayList<>(container.values()));\n } else {\n setException(new ContainerMockNotFoundException(containerName));\n }\n }\n }\n private final class ListObjectsTask\n extends ContainerTaskBase {\n private final String afterObjectId;\n private final Collection<T> outputBuffer;\n private final int limit;\n public ListObjectsTask(\n final String containerName, final String afterObjectId,\n final Collection<T> outputBuffer, final int limit\n ) {\n super(containerName);\n this.afterObjectId = afterObjectId;\n this.outputBuffer = outputBuffer;\n this.limit = limit;\n }\n @Override\n public final void run() {\n final ObjectContainerMock<T> container = getContainer();\n if(container != null) {\n set(container.list(afterObjectId, outputBuffer, limit));\n } else {\n setException();\n }\n }\n }\n private final class DeleteObjectTask\n extends ContainerTaskBase {\n private final String objectId;\n public DeleteObjectTask(final String containerName, final String objectId) {\n super(containerName);\n this.objectId = objectId;\n }\n @Override\n public final void run() {\n final ObjectContainerMock<T> container = getContainer();\n if(container != null) {\n set(container.remove(objectId));\n } else {\n setException();\n }\n }\n }\n private final class GetObjectTask\n extends ContainerTaskBase {\n private final String objectId;\n public GetObjectTask(final String containerName, final String objectId) {\n super(containerName);\n this.objectId = objectId;\n }\n @Override\n public final void run() {\n final ObjectContainerMock<T> container = getContainer();\n if(container != null) {\n set(container.get(objectId));\n } else {\n setException();\n }\n }\n }\n private final class PutObjectTask\n extends ContainerTaskBase {\n private T object;\n public PutObjectTask(final String containerName, final T object) {\n super(containerName);\n this.object = object;\n }\n @Override\n public final void run() {\n final ObjectContainerMock<T> container =\n getContainer();\n if(container != null) {\n set(container.put(object.getName(), object));\n } else {\n setException();\n }\n }\n }\n private final class DeleteContainerTask\n extends FutureTaskBase<ObjectContainerMock<T>> {\n private final String containerName;\n public DeleteContainerTask(final String containerName) {\n this.containerName = containerName;\n }\n @Override\n public final void run() {\n if(storageMap.containsKey(containerName)) {\n set(storageMap.remove(containerName));\n } else {\n setException(new ContainerMockNotFoundException(containerName));\n }\n }\n }\n private final class GetContainerTask\n extends FutureTaskBase<ObjectContainerMock<T>> {\n private final String containerName;\n public GetContainerTask(final String containerName) {\n this.containerName = containerName;\n }\n @Override\n public final void run() {\n if(storageMap.containsKey(containerName)) {\n set(storageMap.get(containerName));\n } else {\n setException(new ContainerMockNotFoundException(containerName));\n }\n }\n }\n private final class PutContainerTask\n extends FutureTaskBase<ObjectContainerMock<T>> {\n private final String containerName;\n public PutContainerTask(final String containerName) {\n this.containerName = containerName;\n }\n @Override\n public final void run() {\n set(storageMap.put(containerName, new BasicObjectContainerMock<>(containerCapacity)));\n ioStats.containerCreate();\n }\n }\n}"}}},{"rowIdx":1297,"cells":{"answer":{"kind":"string","value":"package org.duracloud.swiftstorage;\nimport static org.duracloud.common.error.RetryFlaggableException.NO_RETRY;\nimport static org.duracloud.common.error.RetryFlaggableException.RETRY;\nimport static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_CHECKSUM;\nimport static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_MD5;\nimport static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_MIMETYPE;\nimport static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_MODIFIED;\nimport static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_SIZE;\nimport static org.duracloud.storage.provider.StorageProvider.PROPERTIES_SPACE_COUNT;\nimport static org.duracloud.storage.provider.StorageProvider.PROPERTIES_SPACE_CREATED;\nimport java.lang.reflect.Field;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.amazonaws.AmazonClientException;\nimport com.amazonaws.services.s3.AmazonS3;\nimport com.amazonaws.services.s3.Headers;\nimport com.amazonaws.services.s3.model.AccessControlList;\nimport com.amazonaws.services.s3.model.AmazonS3Exception;\nimport com.amazonaws.services.s3.model.Bucket;\nimport com.amazonaws.services.s3.model.CopyObjectRequest;\nimport com.amazonaws.services.s3.model.ObjectMetadata;\nimport org.apache.commons.lang.StringUtils;\nimport org.duracloud.common.constant.Constants;\nimport org.duracloud.common.rest.HttpHeaders;\nimport org.duracloud.s3storage.S3ProviderUtil;\nimport org.duracloud.s3storage.S3StorageProvider;\nimport org.duracloud.storage.domain.StorageProviderType;\nimport org.duracloud.storage.error.NotFoundException;\nimport org.duracloud.storage.error.StorageException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\npublic class SwiftStorageProvider extends S3StorageProvider {\n private final Logger log =\n LoggerFactory.getLogger(SwiftStorageProvider.class);\n public SwiftStorageProvider(String accessKey, String secretKey, Map<String, String> options) {\n super(accessKey, secretKey, options);\n }\n public SwiftStorageProvider(AmazonS3 s3Client, String accessKey) {\n super(s3Client, accessKey, null);\n }\n private static String[] SWIFT_METADATA_LIST =\n {Headers.ETAG, Headers.CONTENT_LENGTH, Headers.DATE, Headers.LAST_MODIFIED, Headers.CONTENT_TYPE};\n /**\n * {@inheritDoc}\n */\n @Override\n public StorageProviderType getStorageProviderType() {\n return StorageProviderType.SWIFT_S3;\n }\n @Override\n protected Bucket createBucket(String spaceId) {\n String bucketName = getNewBucketName(spaceId);\n try {\n Bucket bucket = s3Client.createBucket(bucketName);\n // Swift has no concept of bucket lifecycle\n return bucket;\n } catch (AmazonClientException e) {\n String err = \"Could not create Swift container with name \" + bucketName\n + \" due to error: \" + e.getMessage();\n throw new StorageException(err, e, RETRY);\n }\n }\n @Override\n public void removeSpace(String spaceId) {\n // Will throw if bucket does not exist\n String bucketName = getBucketName(spaceId);\n String propertiesBucketName = getBucketName(PROPERTIES_BUCKET);\n try {\n s3Client.deleteBucket(bucketName);\n } catch (AmazonClientException e) {\n String err = \"Could not delete Swift container with name \" + bucketName\n + \" due to error: \" + e.getMessage();\n throw new StorageException(err, e, RETRY);\n }\n // Space properties are stored as tags with the S3 bucket.\n // So with Swift we need to delete the associated properties object in Swift.\n s3Client.deleteObject(propertiesBucketName, spaceId);\n }\n @Override\n public String createHiddenSpace(String spaceId, int expirationInDays) {\n String bucketName = getHiddenBucketName(spaceId);\n try {\n Bucket bucket = s3Client.createBucket(bucketName);\n return spaceId;\n } catch (AmazonClientException e) {\n String err = \"Could not create Swift container with name \" + bucketName\n + \" due to error: \" + e.getMessage();\n throw new StorageException(err, e, RETRY);\n }\n }\n // Swift access keys are longer than 20 characters, and creating\n // a bucket starting with your access key causes problems.\n @Override\n protected String getNewBucketName(String spaceId) {\n String truncatedKey = truncateKey(accessKeyId);\n return S3ProviderUtil.createNewBucketName(truncatedKey, spaceId);\n }\n @Override\n protected String getSpaceId(String bucketName) {\n String spaceId = bucketName;\n String truncatedKey = truncateKey(accessKeyId);\n if (isSpace(bucketName)) {\n spaceId = spaceId.substring(truncatedKey.length() + 1);\n }\n return spaceId;\n }\n @Override\n protected Map<String, String> getAllSpaceProperties(String spaceId) {\n log.debug(\"getAllSpaceProperties(\" + spaceId + \")\");\n // Will throw if bucket does not exist\n String propsBucketName = getBucketName(PROPERTIES_BUCKET);\n Map<String, String> spaceProperties = new HashMap<>();\n String spacePropertiesString;\n try {\n spacePropertiesString = s3Client.getObjectAsString(propsBucketName, spaceId);\n // Remove the {} from the string\n spacePropertiesString =\n spacePropertiesString.substring(1, spacePropertiesString.length() - 1);\n String[] spacePropertiesList = spacePropertiesString.split(\", \");\n for (String property : spacePropertiesList) {\n String[] props = property.split(\"=\");\n spaceProperties.put(props[0], props[1]);\n }\n } catch (AmazonS3Exception e) {\n // If no space properties have been set yet, then the object will not exist.\n // But we don't need to create it here, as it gets created when properties are set.\n log.debug(\n \"Metadata object for space \" + spaceId +\n \" was not found in container \" + propsBucketName +\n \", probably because this is a new space.\"\n );\n }\n // Handle @ symbol (change from +), to allow for email usernames in ACLs\n spaceProperties = replaceInMapValues(spaceProperties, \"+\", \"@\");\n // Add space count\n spaceProperties.put(PROPERTIES_SPACE_COUNT,\n getSpaceCount(spaceId, MAX_ITEM_COUNT));\n return spaceProperties;\n }\n @Override\n protected void doSetSpaceProperties(String spaceId,\n Map<String, String> spaceProperties) {\n log.debug(\"setSpaceProperties(\" + spaceId + \")\");\n Map<String, String> originalProperties;\n try {\n originalProperties = getAllSpaceProperties(spaceId);\n } catch (NotFoundException e) {\n // The metadata bucket does not exist yet, so create it\n createHiddenSpace(PROPERTIES_BUCKET, 0);\n // And set the original properties to a new, empty HashMap\n originalProperties = new HashMap<>();\n }\n // By calling this _after_ we have requested the space properties,\n // we ensure that the metadata bucket exists.\n String metadataBucketName = getBucketName(PROPERTIES_BUCKET);\n // Set creation date\n String creationDate = originalProperties.get(PROPERTIES_SPACE_CREATED);\n if (creationDate == null) {\n creationDate = spaceProperties.get(PROPERTIES_SPACE_CREATED);\n if (creationDate == null) {\n // getCreationDate() does not work properly on Swift\n creationDate = formattedDate(new Date());\n }\n }\n spaceProperties.put(PROPERTIES_SPACE_CREATED, creationDate);\n // Handle @ symbol (change to +), to allow for email usernames in ACLs\n spaceProperties = replaceInMapValues(spaceProperties, \"@\", \"+\");\n // Store properties in an object in the hidden metadata bucket\n log.debug(\n \"Writing space properties \" + spaceProperties.toString() +\n \" to object \" + spaceId +\n \" in Swift container \" + metadataBucketName\n );\n s3Client.putObject(metadataBucketName, spaceId, spaceProperties.toString());\n }\n @Override\n protected void updateObjectProperties(String bucketName,\n String contentId,\n ObjectMetadata objMetadata) {\n try {\n AccessControlList originalACL =\n s3Client.getObjectAcl(bucketName, contentId);\n CopyObjectRequest copyRequest = new CopyObjectRequest(bucketName,\n contentId,\n bucketName,\n contentId);\n copyRequest.setStorageClass(DEFAULT_STORAGE_CLASS);\n copyRequest.setNewObjectMetadata(objMetadata);\n // Setting object ACLs resets an object's ContentType to application/xml!\n // But setting the ACLs before we do the copy request gets around this.\n copyRequest.setAccessControlList(originalACL);\n s3Client.copyObject(copyRequest);\n } catch (AmazonClientException e) {\n throwIfContentNotExist(bucketName, contentId);\n String err = \"Could not update metadata for content \" + contentId + \" in Swift container \" +\n bucketName + \" due to error: \" + e.getMessage();\n throw new StorageException(err, e, NO_RETRY);\n }\n }\n @Override\n protected Map<String, String> prepContentProperties(ObjectMetadata objMetadata) {\n Map<String, String> contentProperties = new HashMap<>();\n // Set the user properties\n Map<String, String> userProperties = objMetadata.getUserMetadata();\n for (String metaName : userProperties.keySet()) {\n String metaValue = userProperties.get(metaName);\n if (metaName.trim().equalsIgnoreCase(\"tags\") ||\n metaName.trim().equalsIgnoreCase(\"tags\" + HEADER_KEY_SUFFIX) ||\n metaName.trim().equalsIgnoreCase(PROPERTIES_CONTENT_MIMETYPE) ||\n metaName.trim().equalsIgnoreCase(PROPERTIES_CONTENT_MIMETYPE + HEADER_KEY_SUFFIX)) {\n metaName = metaName.toLowerCase();\n }\n contentProperties.put(getWithSpace(decodeHeaderKey(metaName)), decodeHeaderValue(metaValue));\n }\n // Set the response metadata\n Map<String, Object> responseMeta = objMetadata.getRawMetadata();\n for (String metaName : responseMeta.keySet()) {\n // Don't include Swift response headers\n try {\n if (!isSwiftMetadata(metaName)) {\n Object metaValue = responseMeta.get(metaName);\n // Remove extra Swift metadata from user properties section\n for (String swiftMetaName : SWIFT_METADATA_LIST) {\n if (metaName.trim().equalsIgnoreCase(swiftMetaName)) {\n metaName = swiftMetaName;\n }\n }\n contentProperties.put(metaName, String.valueOf(metaValue));\n }\n } catch (IllegalArgumentException e) {\n e.printStackTrace();\n }\n // Remove User Response headers that are also in RawMetadata\n // Swift metadata are non-standard HTTP headers so DuraCloud views them as \"User\" metadata\n if (userProperties.keySet()\n .contains(metaName + HEADER_KEY_SUFFIX) && contentProperties.containsKey(metaName)) {\n contentProperties.remove(metaName);\n }\n }\n // Set MIMETYPE\n String contentType = objMetadata.getContentType();\n if (contentType != null) {\n contentProperties.put(PROPERTIES_CONTENT_MIMETYPE, contentType);\n contentProperties.put(Headers.CONTENT_TYPE, contentType);\n }\n // Set CONTENT_ENCODING\n String encoding = objMetadata.getContentEncoding();\n if (encoding != null) {\n contentProperties.put(Headers.CONTENT_ENCODING, encoding);\n }\n // Set SIZE\n long contentLength = objMetadata.getContentLength();\n if (contentLength >= 0) {\n String size = String.valueOf(contentLength);\n contentProperties.put(PROPERTIES_CONTENT_SIZE, size);\n contentProperties.put(Headers.CONTENT_LENGTH, size);\n }\n // Set CHECKSUM\n String checksum = objMetadata.getETag();\n if (checksum != null) {\n String eTagValue = getETagValue(checksum);\n contentProperties.put(PROPERTIES_CONTENT_CHECKSUM, eTagValue);\n contentProperties.put(PROPERTIES_CONTENT_MD5, eTagValue);\n contentProperties.put(Headers.ETAG, eTagValue);\n }\n // Set MODIFIED\n Date modified = objMetadata.getLastModified();\n if (modified != null) {\n String modDate = formattedDate(modified);\n contentProperties.put(PROPERTIES_CONTENT_MODIFIED, modDate);\n contentProperties.put(Headers.LAST_MODIFIED, modDate);\n }\n return contentProperties;\n }\n private String truncateKey(String accessKey) {\n // Convert access key to 20 character string\n return StringUtils.left(accessKey, 20);\n }\n private boolean isSwiftMetadata(String metaName) {\n Field[] httpFields = HttpHeaders.class.getFields();\n for (Field f : httpFields) {\n String fieldName = null;\n try {\n fieldName = (String) f.get(httpFields);\n } catch (IllegalArgumentException | IllegalAccessException e) {\n e.printStackTrace();\n }\n if (metaName.equalsIgnoreCase(fieldName)) {\n return false;\n }\n }\n return true;\n }\n /**\n * Add expire header for object in Swift.\n * @param bucketName\n * @param contentId\n * @param seconds\n */\n public ObjectMetadata expireObject(String bucketName, String contentId, Integer seconds) {\n log.debug(\"Expiring object {} in {} after {} seconds.\", contentId, bucketName, seconds);\n ObjectMetadata objMetadata = getObjectDetails(bucketName, contentId, true);\n objMetadata.setHeader(Constants.SWIFT_EXPIRE_OBJECT_HEADER, seconds);\n updateObjectProperties(bucketName, contentId, objMetadata);\n return objMetadata;\n }\n private ObjectMetadata getObjectDetails(String bucketName, String contentId, boolean retry) {\n try {\n return s3Client.getObjectMetadata(bucketName, contentId);\n } catch (AmazonClientException e) {\n throwIfContentNotExist(bucketName, contentId);\n String err = \"Could not get details for content \" + contentId + \" in Swift container \" + bucketName\n + \" due to error: \" + e.getMessage();\n throw new StorageException(err, e, retry);\n }\n }\n}"}}},{"rowIdx":1298,"cells":{"answer":{"kind":"string","value":"package org.telegram.telegrambots.meta.api.objects;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport org.telegram.telegrambots.meta.api.interfaces.BotApiObject;\nimport org.telegram.telegrambots.meta.api.objects.games.Animation;\nimport org.telegram.telegrambots.meta.api.objects.games.Game;\nimport org.telegram.telegrambots.meta.api.objects.passport.PassportData;\nimport org.telegram.telegrambots.meta.api.objects.payments.Invoice;\nimport org.telegram.telegrambots.meta.api.objects.payments.SuccessfulPayment;\nimport org.telegram.telegrambots.meta.api.objects.stickers.Sticker;\nimport java.util.ArrayList;\nimport java.util.List;\n/**\n * @author Ruben Bermudez\n * @version 1.0\n * This object represents a message.\n */\npublic class Message implements BotApiObject {\n private static final String MESSAGEID_FIELD = \"message_id\";\n private static final String FROM_FIELD = \"from\";\n private static final String DATE_FIELD = \"date\";\n private static final String CHAT_FIELD = \"chat\";\n private static final String FORWARDFROM_FIELD = \"forward_from\";\n private static final String FORWARDFROMCHAT_FIELD = \"forward_from_chat\";\n private static final String FORWARDDATE_FIELD = \"forward_date\";\n private static final String TEXT_FIELD = \"text\";\n private static final String ENTITIES_FIELD = \"entities\";\n private static final String CAPTIONENTITIES_FIELD = \"caption_entities\";\n private static final String AUDIO_FIELD = \"audio\";\n private static final String DOCUMENT_FIELD = \"document\";\n private static final String PHOTO_FIELD = \"photo\";\n private static final String STICKER_FIELD = \"sticker\";\n private static final String VIDEO_FIELD = \"video\";\n private static final String CONTACT_FIELD = \"contact\";\n private static final String LOCATION_FIELD = \"location\";\n private static final String VENUE_FIELD = \"venue\";\n private static final String ANIMATION_FIELD = \"animation\";\n private static final String PINNED_MESSAGE_FIELD = \"pinned_message\";\n private static final String NEWCHATMEMBERS_FIELD = \"new_chat_members\";\n private static final String LEFTCHATMEMBER_FIELD = \"left_chat_member\";\n private static final String NEWCHATTITLE_FIELD = \"new_chat_title\";\n private static final String NEWCHATPHOTO_FIELD = \"new_chat_photo\";\n private static final String DELETECHATPHOTO_FIELD = \"delete_chat_photo\";\n private static final String GROUPCHATCREATED_FIELD = \"group_chat_created\";\n private static final String REPLYTOMESSAGE_FIELD = \"reply_to_message\";\n private static final String VOICE_FIELD = \"voice\";\n private static final String CAPTION_FIELD = \"caption\";\n private static final String SUPERGROUPCREATED_FIELD = \"supergroup_chat_created\";\n private static final String CHANNELCHATCREATED_FIELD = \"channel_chat_created\";\n private static final String MIGRATETOCHAT_FIELD = \"migrate_to_chat_id\";\n private static final String MIGRATEFROMCHAT_FIELD = \"migrate_from_chat_id\";\n private static final String EDITDATE_FIELD = \"edit_date\";\n private static final String GAME_FIELD = \"game\";\n private static final String FORWARDFROMMESSAGEID_FIELD = \"forward_from_message_id\";\n private static final String INVOICE_FIELD = \"invoice\";\n private static final String SUCCESSFUL_PAYMENT_FIELD = \"successful_payment\";\n private static final String VIDEO_NOTE_FIELD = \"video_note\";\n private static final String AUTHORSIGNATURE_FIELD = \"author_signature\";\n private static final String FORWARDSIGNATURE_FIELD = \"forward_signature\";\n private static final String MEDIAGROUPID_FIELD = \"media_group_id\";\n private static final String CONNECTEDWEBSITE_FIELD = \"connected_website\";\n private static final String PASSPORTDATA_FIELD = \"passport_data\";\n @JsonProperty(MESSAGEID_FIELD)\n private Integer messageId; ///< Integer Unique message identifier\n @JsonProperty(FROM_FIELD)\n private User from; ///< Optional. Sender, can be empty for messages sent to channels\n @JsonProperty(DATE_FIELD)\n private Integer date; ///< Optional. Date the message was sent in Unix time\n @JsonProperty(CHAT_FIELD)\n private Chat chat; ///< Conversation the message belongs to\n @JsonProperty(FORWARDFROM_FIELD)\n private User forwardFrom; ///< Optional. For forwarded messages, sender of the original message\n @JsonProperty(FORWARDFROMCHAT_FIELD)\n private Chat forwardFromChat; ///< Optional. For messages forwarded from a channel, information about the original channel\n @JsonProperty(FORWARDDATE_FIELD)\n private Integer forwardDate; ///< Optional. For forwarded messages, date the original message was sent\n @JsonProperty(TEXT_FIELD)\n private String text; ///< Optional. For text messages, the actual UTF-8 text of the message\n /**\n * Optional. For text messages, special entities like usernames, URLs,\n * bot commands, etc. that appear in the text\n */\n @JsonProperty(ENTITIES_FIELD)\n private List<MessageEntity> entities;\n /**\n * Optional. For messages with a caption, special entities like usernames,\n * URLs, bot commands, etc. that appear in the caption\n */\n @JsonProperty(CAPTIONENTITIES_FIELD)\n private List<MessageEntity> captionEntities;\n @JsonProperty(AUDIO_FIELD)\n private Audio audio; ///< Optional. Message is an audio file, information about the file\n @JsonProperty(DOCUMENT_FIELD)\n private Document document; ///< Optional. Message is a general file, information about the file\n @JsonProperty(PHOTO_FIELD)\n private List<PhotoSize> photo; ///< Optional. Message is a photo, available sizes of the photo\n @JsonProperty(STICKER_FIELD)\n private Sticker sticker; ///< Optional. Message is a sticker, information about the sticker\n @JsonProperty(VIDEO_FIELD)\n private Video video; ///< Optional. Message is a video, information about the video\n @JsonProperty(CONTACT_FIELD)\n private Contact contact; ///< Optional. Message is a shared contact, information about the contact\n @JsonProperty(LOCATION_FIELD)\n private Location location; ///< Optional. Message is a shared location, information about the location\n @JsonProperty(VENUE_FIELD)\n private Venue venue; ///< Optional. Message is a venue, information about the venue\n /**\n * Optional. Message is an animation, information about the animation.\n * For backward compatibility, when this field is set, the document field will be also set\n */\n @JsonProperty(ANIMATION_FIELD)\n private Animation animation;\n @JsonProperty(PINNED_MESSAGE_FIELD)\n private Message pinnedMessage; ///< Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.\n @JsonProperty(NEWCHATMEMBERS_FIELD)\n private List<User> newChatMembers; ///< Optional. New members were added to the group or supergroup, information about them (the bot itself may be one of these members)\n @JsonProperty(LEFTCHATMEMBER_FIELD)\n private User leftChatMember; ///< Optional. A member was removed from the group, information about them (this member may be bot itself)\n @JsonProperty(NEWCHATTITLE_FIELD)\n private String newChatTitle; ///< Optional. A chat title was changed to this value\n @JsonProperty(NEWCHATPHOTO_FIELD)\n private List<PhotoSize> newChatPhoto; ///< Optional. A chat photo was change to this value\n @JsonProperty(DELETECHATPHOTO_FIELD)\n private Boolean deleteChatPhoto; ///< Optional. Informs that the chat photo was deleted\n @JsonProperty(GROUPCHATCREATED_FIELD)\n private Boolean groupchatCreated; ///< Optional. Informs that the group has been created\n @JsonProperty(REPLYTOMESSAGE_FIELD)\n private Message replyToMessage;\n @JsonProperty(VOICE_FIELD)\n private Voice voice; ///< Optional. Message is a voice message, information about the file\n @JsonProperty(CAPTION_FIELD)\n private String caption; ///< Optional. Caption for the document, photo or video, 0-200 characters\n @JsonProperty(SUPERGROUPCREATED_FIELD)\n private Boolean superGroupCreated;\n @JsonProperty(CHANNELCHATCREATED_FIELD)\n private Boolean channelChatCreated;\n /**\n * Optional. The group has been migrated to a supergroup with the specified identifier.\n * This number may be greater than 32 bits and some programming languages\n * may have difficulty/silent defects in interpreting it.\n * But it smaller than 52 bits, so a signed 64 bit integer or double-precision\n * float type are safe for storing this identifier.\n */\n @JsonProperty(MIGRATETOCHAT_FIELD)\n private Long migrateToChatId; ///< Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value\n /**\n * Optional. The supergroup has been migrated from a group with the specified identifier.\n * This number may be greater than 32 bits and some programming languages\n * may have difficulty/silent defects in interpreting it.\n * But it smaller than 52 bits, so a signed 64 bit integer or double-precision\n * float type are safe for storing this identifier.\n */\n @JsonProperty(MIGRATEFROMCHAT_FIELD)\n private Long migrateFromChatId; ///< Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value\n @JsonProperty(EDITDATE_FIELD)\n private Integer editDate; ///< Optional. Date the message was last edited in Unix time\n @JsonProperty(GAME_FIELD)\n private Game game; ///< Optional. Message is a game, information about the game\n @JsonProperty(FORWARDFROMMESSAGEID_FIELD)\n private Integer forwardFromMessageId; ///< Optional. For forwarded channel posts, identifier of the original message in the channel\n @JsonProperty(INVOICE_FIELD)\n private Invoice invoice; ///< Optional. Message is an invoice for a payment, information about the invoice.\n @JsonProperty(SUCCESSFUL_PAYMENT_FIELD)\n private SuccessfulPayment successfulPayment; ///< Optional. Message is a service message about a successful payment, information about the payment.\n @JsonProperty(VIDEO_NOTE_FIELD)\n private VideoNote videoNote; ///< Optional. Message is a video note, information about the video message\n @JsonProperty(AUTHORSIGNATURE_FIELD)\n private String authorSignature; ///< Optional. Post author signature for posts in channel chats\n @JsonProperty(FORWARDSIGNATURE_FIELD)\n private String forwardSignature; ///< Optional. Post author signature for messages forwarded from channel chats\n @JsonProperty(MEDIAGROUPID_FIELD)\n private String mediaGroupId; ///< Optional. The unique identifier of a media message group this message belongs to\n @JsonProperty(CONNECTEDWEBSITE_FIELD)\n private String connectedWebsite; ///< Optional. The domain name of the website on which the user has logged in\n @JsonProperty(PASSPORTDATA_FIELD)\n private PassportData passportData; ///< Optional. Telegram Passport data\n public Message() {\n super();\n }\n public Integer getMessageId() {\n return messageId;\n }\n public User getFrom() {\n return from;\n }\n public Integer getDate() {\n return date;\n }\n public Chat getChat() {\n return chat;\n }\n public User getForwardFrom() {\n return forwardFrom;\n }\n public Integer getForwardDate() {\n return forwardDate;\n }\n public String getText() {\n return text;\n }\n public List<MessageEntity> getEntities() {\n if (entities != null) {\n entities.forEach(x -> x.computeText(text));\n }\n return entities;\n }\n public List<MessageEntity> getCaptionEntities() {\n if (captionEntities != null) {\n captionEntities.forEach(x -> x.computeText(caption));\n }\n return captionEntities;\n }\n public Audio getAudio() {\n return audio;\n }\n public Document getDocument() {\n return document;\n }\n public List<PhotoSize> getPhoto() {\n return photo;\n }\n public Sticker getSticker() {\n return sticker;\n }\n public boolean hasSticker() {\n return sticker != null;\n }\n public Video getVideo() {\n return video;\n }\n public Animation getAnimation() {\n return animation;\n }\n public Contact getContact() {\n return contact;\n }\n public Location getLocation() {\n return location;\n }\n public Venue getVenue() {\n return venue;\n }\n public Message getPinnedMessage() {\n return pinnedMessage;\n }\n public List<User> getNewChatMembers() {\n return newChatMembers == null ? new ArrayList<>() : newChatMembers;\n }\n public User getLeftChatMember() {\n return leftChatMember;\n }\n public String getNewChatTitle() {\n return newChatTitle;\n }\n public List<PhotoSize> getNewChatPhoto() {\n return newChatPhoto;\n }\n public Boolean getDeleteChatPhoto() {\n return deleteChatPhoto;\n }\n public Boolean getGroupchatCreated() {\n return groupchatCreated;\n }\n public Message getReplyToMessage() {\n return replyToMessage;\n }\n public Voice getVoice() {\n return voice;\n }\n public String getCaption() {\n return caption;\n }\n public Boolean getSuperGroupCreated() {\n return superGroupCreated;\n }\n public Boolean getChannelChatCreated() {\n return channelChatCreated;\n }\n public Long getMigrateToChatId() {\n return migrateToChatId;\n }\n public Long getMigrateFromChatId() {\n return migrateFromChatId;\n }\n public Integer getForwardFromMessageId() {\n return forwardFromMessageId;\n }\n public boolean isGroupMessage() {\n return chat.isGroupChat();\n }\n public boolean isUserMessage() {\n return chat.isUserChat();\n }\n public boolean isChannelMessage() {\n return chat.isChannelChat();\n }\n public boolean isSuperGroupMessage() {\n return chat.isSuperGroupChat();\n }\n public Long getChatId() {\n return chat.getId();\n }\n public boolean hasText() {\n return text != null && !text.isEmpty();\n }\n public boolean isCommand() {\n if (hasText() && entities != null) {\n for (MessageEntity entity : entities) {\n if (entity != null && entity.getOffset() == 0 &&\n EntityType.BOTCOMMAND.equals(entity.getType())) {\n return true;\n }\n }\n }\n return false;\n }\n public boolean hasDocument() {\n return this.document != null;\n }\n public boolean hasVideo() {\n return this.video != null;\n }\n public boolean hasAudio(){\n return this.audio != null;\n }\n public boolean hasVoice(){\n return this.voice != null;\n }\n public boolean isReply() {\n return this.replyToMessage != null;\n }\n public boolean hasLocation() {\n return location != null;\n }\n public Chat getForwardFromChat() {\n return forwardFromChat;\n }\n public Integer getEditDate() {\n return editDate;\n }\n public Game getGame() {\n return game;\n }\n private boolean hasGame() {\n return game != null;\n }\n public boolean hasEntities() {\n return entities != null && !entities.isEmpty();\n }\n public boolean hasPhoto() {\n return photo != null && !photo.isEmpty();\n }\n public boolean hasInvoice() {\n return invoice != null;\n }\n public boolean hasSuccessfulPayment() {\n return successfulPayment != null;\n }\n public boolean hasContact() {\n return contact != null;\n }\n public Invoice getInvoice() {\n return invoice;\n }\n public SuccessfulPayment getSuccessfulPayment() {\n return successfulPayment;\n }\n public VideoNote getVideoNote() {\n return videoNote;\n }\n public boolean hasVideoNote() {\n return videoNote != null;\n }\n public String getAuthorSignature() {\n return authorSignature;\n }\n public String getForwardSignature() {\n return forwardSignature;\n }\n public String getMediaGroupId() {\n return mediaGroupId;\n }\n public String getConnectedWebsite() {\n return connectedWebsite;\n }\n public PassportData getPassportData() {\n return passportData;\n }\n public boolean hasPassportData() {\n return passportData != null;\n }\n public boolean hasAnimation() {\n return animation != null;\n }\n @Override\n public String toString() {\n return \"Message{\" +\n \"messageId=\" + messageId +\n \", from=\" + from +\n \", date=\" + date +\n \", chat=\" + chat +\n \", forwardFrom=\" + forwardFrom +\n \", forwardFromChat=\" + forwardFromChat +\n \", forwardDate=\" + forwardDate +\n \", text='\" + text + '\\'' +\n \", entities=\" + entities +\n \", captionEntities=\" + captionEntities +\n \", audio=\" + audio +\n \", document=\" + document +\n \", photo=\" + photo +\n \", sticker=\" + sticker +\n \", video=\" + video +\n \", contact=\" + contact +\n \", location=\" + location +\n \", venue=\" + venue +\n \", pinnedMessage=\" + pinnedMessage +\n \", newChatMembers=\" + newChatMembers +\n \", leftChatMember=\" + leftChatMember +\n \", newChatTitle='\" + newChatTitle + '\\'' +\n \", newChatPhoto=\" + newChatPhoto +\n \", deleteChatPhoto=\" + deleteChatPhoto +\n \", groupchatCreated=\" + groupchatCreated +\n \", replyToMessage=\" + replyToMessage +\n \", voice=\" + voice +\n \", caption='\" + caption + '\\'' +\n \", superGroupCreated=\" + superGroupCreated +\n \", channelChatCreated=\" + channelChatCreated +\n \", migrateToChatId=\" + migrateToChatId +\n \", migrateFromChatId=\" + migrateFromChatId +\n \", editDate=\" + editDate +\n \", game=\" + game +\n \", forwardFromMessageId=\" + forwardFromMessageId +\n \", invoice=\" + invoice +\n \", successfulPayment=\" + successfulPayment +\n \", videoNote=\" + videoNote +\n \", authorSignature='\" + authorSignature + '\\'' +\n \", forwardSignature='\" + forwardSignature + '\\'' +\n \", mediaGroupId='\" + mediaGroupId + '\\'' +\n \", connectedWebsite='\" + connectedWebsite + '\\'' +\n \", passportData=\" + passportData +\n '}';\n }\n}"}}},{"rowIdx":1299,"cells":{"answer":{"kind":"string","value":"// TODO : les todos\npackage client;\nimport java.net.MalformedURLException;\nimport java.rmi.AlreadyBoundException;\nimport java.rmi.Naming;\nimport java.rmi.RemoteException;\nimport java.rmi.registry.LocateRegistry;\nimport java.rmi.registry.Registry;\nimport java.rmi.server.UnicastRemoteObject;\nimport java.util.UUID;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Set;\nimport commun.ClientInfo;\nimport commun.DejaConnecteException;\nimport commun.IClient;\nimport commun.IHotelDesVentes;\nimport commun.Objet;\nimport commun.PasCreateurException;\nimport commun.PseudoDejaUtiliseException;\nimport commun.SalleDeVenteInfo;\nimport commun.ServeurInfo;\nimport commun.Message;\npublic class Client extends UnicastRemoteObject implements IClient {\n private static final long serialVersionUID = 1L;\n private String urlEtPortServeur;\n private String adresseServeur;\n public ServeurInfo serveur;\n public String getAdresseClient() {\n return myClientInfos.getAdresseClient();\n }\n private IHotelDesVentes hdv=null;\n private HashMap<UUID, Objet> ventesSuivies;\n private HashMap<UUID, SalleDeVenteInfo> mapInfosSalles;\n private HashMap<UUID, List<Message>> listesMessages;\n public ClientInfo myClientInfos;\n private UUID idSalleObservee;\n private String nomSalleObservee;\n private UUID idObjetObserve;\n private String nomObjetObserve;\n public void setIdSalleObservee(UUID idSalleObservee) {\n this.idSalleObservee = idSalleObservee;\n }\n public Client(String nom,String ipServeurSaisi, String portServeurSaisi) throws RemoteException {\n super();\n this.myClientInfos = new ClientInfo(UUID.randomUUID(),nom, \"127.0.0.1\", \"8092\");\n serveur= new ServeurInfo(ipServeurSaisi,portServeurSaisi);\n d(serveur.getAdresseServeur());\n connexionServeur();\n this.ventesSuivies = new HashMap<UUID, Objet>();\n }\n public void connexionServeur() {\n d(\"Tentative d'initialisation de hdv à l'adresse:\"+serveur.getAdresseServeur());\n while(hdv==null) {\n try {\n hdv = (IHotelDesVentes) Naming.lookup(serveur.getAdresseServeur());\n System.out.println(\"Connexion au serveur \" + serveur.getAdresseServeur() + \" reussi.\");\n } catch (Exception e) {\n System.out.println(\"Connexion au serveur \" + serveur.getAdresseServeur() + \" impossible.\");\n }\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n }\n public void connexion () {\n try {\n mapInfosSalles = hdv.login(this.myClientInfos);\n } catch (RemoteException | PseudoDejaUtiliseException | DejaConnecteException e) {\n e.printStackTrace();\n }\n }\n public void deconnexion () {\n try {\n hdv.logout(myClientInfos);\n } catch (RemoteException e) {\n e.printStackTrace();\n }\n // TODO : fermeture de l'application ?\n }\n public void nouvelleSoumission(String nom, String description, int prix, UUID idSdv) throws RemoteException {\n Objet nouveau = new Objet(nom, description, prix,myClientInfos.getNom());\n //ajout de l'objet par le hdv\n try {\n hdv.ajouterObjet(nouveau, idSdv, getId());\n } catch (PasCreateurException e) {\n e.printStackTrace();\n }\n //print des informations sur l'ajout\n }\n public void nouvelleSalle(String nom, String description, float f) throws RemoteException {\n Objet nouveau = new Objet(nom, description, f,myClientInfos.getNom());\n System.out.println(\"\"+myClientInfos.getAdresseClient()+\" \"+myClientInfos.getNom()+\" \"+getId()+\" \"+nouveau+\" \"+myClientInfos.getNom()+\" \\n\");\n hdv.creerSalle(myClientInfos, nouveau, \"Salle de \"+myClientInfos.getNom());\n }\n public void pingServeur() throws RemoteException {\n if ( hdv==null) System.out.print(\"Hdv null : connexion pas effectué\\n\");\n hdv.ping();\n }\n public static void main(String[] argv) {\n try {\n //start IHM\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n public IHotelDesVentes getServeur() {\n return hdv;\n }\n public void setServeur(IHotelDesVentes serveur) {\n this.hdv = serveur;\n }\n // notification au serveur de la fermeture d'une salle par le client\n public void fermetureSalle(UUID idSDV) {\n try {\n hdv.fermerSalle(idSDV, getId());\n } catch (PasCreateurException e) {\n e.printStackTrace();\n } catch (RemoteException e) {\n e.printStackTrace();\n }\n }\n public void rejoindreSalle(UUID idSalle) {\n try {\n Objet obj = hdv.rejoindreSalle(idSalle, this.myClientInfos);\n ventesSuivies.put(idSalle, obj);\n // TODO : refresh l'IHM pour prendre en compte les modifs\n } catch (RemoteException e) {\n e.printStackTrace();\n // TODO : affichage d'un message d'erreur par l'IHM\n }\n }\n public HashMap<UUID, Objet> getVentesSuivies() {\n return ventesSuivies;\n }\n @Override\n public void nouveauMessage(UUID idSalle, Message message) {\n listesMessages.get(idSalle).add(message);\n // TODO : refresh l'IHM pour prendre en compte les modifs\n }\n @Override\n public void notifModifObjet(UUID idSalle, Objet objet) {\n ventesSuivies.put(idSalle, objet);\n mapInfosSalles.get(idSalle).setObjCourrant(objet);\n // TODO : refresh l'IHM pour prendre en compte les modifs\n }\n @Override\n public void notifFermetureSalle(UUID idSalle) {\n ventesSuivies.remove(idSalle);\n mapInfosSalles.remove(idSalle);\n // TODO : refresh l'IHM pour prendre en compte les modifs\n }\n @Override\n public void notifNouvelleSalle(UUID idsdv, SalleDeVenteInfo sdvi) {\n mapInfosSalles.put(idsdv, sdvi);\n }\n public UUID getIdSalleObservee() {\n return this.idSalleObservee;\n }\n public HashMap<UUID, SalleDeVenteInfo> getMapInfosSalles() {\n return mapInfosSalles;\n }\n public void setMapInfosSalles(HashMap<UUID, SalleDeVenteInfo> mapInfosSalles) {\n this.mapInfosSalles = mapInfosSalles;\n }\n public SalleDeVenteInfo[] getTabInfosSalles() {\n if (mapInfosSalles != null) {\n Collection<SalleDeVenteInfo> vals = mapInfosSalles.values();\n SalleDeVenteInfo[] tab = new SalleDeVenteInfo[vals.size()];\n int i = 0;\n for (SalleDeVenteInfo sdvi : vals) {\n tab[i] = sdvi;\n ++i;\n }\n return tab;\n }\n // TODO : lever une exception ?\n else return new SalleDeVenteInfo[0];\n }\n public SalleDeVenteInfo[] getTabVentesSuivies() {\n if (ventesSuivies != null) {\n Set<UUID> keys = ventesSuivies.keySet();\n SalleDeVenteInfo[] tab = new SalleDeVenteInfo[keys.size()];\n int i = 0;\n for (UUID idSalle : keys) {\n tab[i] = mapInfosSalles.get(idSalle);\n ++i;\n }\n return tab;\n }\n // TODO : lever une exception ?\n else return new SalleDeVenteInfo[0];\n }\n public void quitterSalle(UUID idSalleAQuitter) {\n try {\n hdv.quitterSalle( getId(),idSalleAQuitter);\n } catch (RemoteException e) {\n e.printStackTrace();\n }\n }\n public UUID getId() {\n return myClientInfos.getId();\n }\n public String getPortClient() {\n return myClientInfos.getPort();\n }\n public void setPortClient(String portClient) {\n myClientInfos.setPort(portClient);\n }\n public void bindClient() {\n Boolean flagRegistreOkay=false;\n while(!flagRegistreOkay) {\n try {\n Registry r = LocateRegistry.getRegistry(Integer.parseInt(serveur.getPort()));\n if (r==null) {\n r=LocateRegistry.createRegistry(Integer.parseInt(serveur.getPort()));\n d(\"Registre créé au port \"+serveur.getPort());\n }else {\n d(\"Registre trouvé au port \"+serveur.getPort());\n }\n flagRegistreOkay=true;\n } catch (NumberFormatException e1) {\n // TODO Auto-generated catch block\n e1.printStackTrace();\n } catch (RemoteException e1) {\n // TODO Auto-generated catch block\n e1.printStackTrace();\n }\n setPortClient( Integer.toString(Integer.parseInt(getPortClient())+1) );\n }\n d(\"Tentative de bind à \"+getAdresseClient());\n try {\n Naming.bind(getAdresseClient(), this);\n } catch(AlreadyBoundException alreadyBoundException) {\n d(\"LOL:AlreadyBound\");\n } catch (MalformedURLException e1) {\n // TODO Auto-generated catch block\n e1.printStackTrace();\n } catch (RemoteException e1) {\n // TODO Auto-generated catch block\n e1.printStackTrace();\n }\n d(\"bind effectué\");\n }\n public static void d(String msg) {\n System.out.println(msg+\"\\n\");\n }\n}"}}}],"truncated":false,"partial":true},"paginationData":{"pageIndex":12,"numItemsPerPage":100,"numTotalItems":346357,"offset":1200,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc2NTcxMDU0Mywic3ViIjoiL2RhdGFzZXRzL3NhbmpheWt6L0phdmEtY29kZSIsImV4cCI6MTc2NTcxNDE0MywiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.DgeXLKWSk3go1ztp_yPggZICeVJld4kOq6EsBOeerDLpvTpdbBG13RDps_D1laKLlP-UN9CJJTuqviPf3cgLDg","displayUrls":true,"splitSizeSummaries":[{"config":"default","split":"train","numRows":346357,"numBytesParquet":1472152454}]},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}"><div><header class="bg-linear-to-t border-b border-gray-100 pt-4 xl:pt-0 from-purple-500/8 dark:from-purple-500/20 to-white to-70% dark:to-gray-950"><div class="mx-4 relative flex flex-col xl:flex-row"><h1 class="flex flex-wrap items-center max-md:leading-tight gap-y-1 text-lg xl:flex-none"><a href="/datasets" class="group flex items-center"><svg class="sm:mr-1 -mr-1 text-gray-400" style="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 25 25"><ellipse cx="12.5" cy="5" fill="currentColor" fill-opacity="0.25" rx="7.5" ry="2"></ellipse><path d="M12.5 15C16.6421 15 20 14.1046 20 13V20C20 21.1046 16.6421 22 12.5 22C8.35786 22 5 21.1046 5 20V13C5 14.1046 8.35786 15 12.5 15Z" fill="currentColor" opacity="0.5"></path><path d="M12.5 7C16.6421 7 20 6.10457 20 5V11.5C20 12.6046 16.6421 13.5 12.5 13.5C8.35786 13.5 5 12.6046 5 11.5V5C5 6.10457 8.35786 7 12.5 7Z" fill="currentColor" opacity="0.5"></path><path d="M5.23628 12C5.08204 12.1598 5 12.8273 5 13C5 14.1046 8.35786 15 12.5 15C16.6421 15 20 14.1046 20 13C20 12.8273 19.918 12.1598 19.7637 12C18.9311 12.8626 15.9947 13.5 12.5 13.5C9.0053 13.5 6.06886 12.8626 5.23628 12Z" fill="currentColor"></path></svg> <span class="mr-2.5 font-semibold text-gray-400 group-hover:text-gray-500 max-sm:hidden">Datasets:</span></a> <hr class="mx-1.5 h-2 translate-y-px rounded-sm border-r dark:border-gray-600 sm:hidden"> <div class="group flex flex-none items-center"><div class="relative mr-1 flex items-center"> <span class="inline-block "><span class="contents"><a href="/sanjaykz" class="text-gray-400 hover:text-blue-600"><img alt="" class="size-3.5 rounded-full flex-none select-none" src="/avatars/d19ed0153ff0b41948819c50ea64e16d.svg" crossorigin="anonymous"></a></span> </span></div> <span class="inline-block "><span class="contents"><a href="/sanjaykz" class="text-gray-400 hover:text-blue-600">sanjaykz</a></span> </span> <div class="mx-0.5 text-gray-300">/</div></div> <div class="max-w-full xl:flex xl:min-w-0 xl:flex-nowrap xl:items-center xl:gap-x-1"><a class="break-words font-mono font-semibold hover:text-blue-600 text-[1.07rem] xl:truncate" href="/datasets/sanjaykz/Java-code">Java-code</a> <button class="text-xs mr-3 focus:outline-hidden inline-flex cursor-pointer items-center text-sm mx-0.5 text-gray-600 " title="Copy dataset name to clipboard" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> </button></div> <div class="inline-flex items-center overflow-hidden whitespace-nowrap rounded-md border bg-white text-sm leading-none text-gray-500 mr-2"><button class="relative flex items-center overflow-hidden from-red-50 to-transparent dark:from-red-900 px-1.5 py-1 hover:bg-linear-to-t focus:outline-hidden" title="Like"><svg class="left-1.5 absolute" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32" fill="currentColor"><path d="M22.45,6a5.47,5.47,0,0,1,3.91,1.64,5.7,5.7,0,0,1,0,8L16,26.13,5.64,15.64a5.7,5.7,0,0,1,0-8,5.48,5.48,0,0,1,7.82,0L16,10.24l2.53-2.58A5.44,5.44,0,0,1,22.45,6m0-2a7.47,7.47,0,0,0-5.34,2.24L16,7.36,14.89,6.24a7.49,7.49,0,0,0-10.68,0,7.72,7.72,0,0,0,0,10.82L16,29,27.79,17.06a7.72,7.72,0,0,0,0-10.82A7.49,7.49,0,0,0,22.45,4Z"></path></svg> <span class="ml-4 pl-0.5 ">like</span></button> <button class="focus:outline-hidden flex items-center border-l px-1.5 py-1 text-gray-400 hover:bg-gray-50 focus:bg-gray-100 dark:hover:bg-gray-900 dark:focus:bg-gray-800" title="See users who liked this repository">2</button></div> </h1> <div class="flex flex-col-reverse gap-x-2 sm:flex-row sm:items-center sm:justify-between xl:ml-auto"><div class="-mb-px flex h-12 items-center overflow-x-auto overflow-y-hidden "> <a class="tab-alternate" href="/datasets/sanjaykz/Java-code"><svg class="mr-1.5 text-gray-400 flex-none" style="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path class="uim-quaternary" d="M20.23 7.24L12 12L3.77 7.24a1.98 1.98 0 0 1 .7-.71L11 2.76c.62-.35 1.38-.35 2 0l6.53 3.77c.29.173.531.418.7.71z" opacity=".25" fill="currentColor"></path><path class="uim-tertiary" d="M12 12v9.5a2.09 2.09 0 0 1-.91-.21L4.5 17.48a2.003 2.003 0 0 1-1-1.73v-7.5a2.06 2.06 0 0 1 .27-1.01L12 12z" opacity=".5" fill="currentColor"></path><path class="uim-primary" d="M20.5 8.25v7.5a2.003 2.003 0 0 1-1 1.73l-6.62 3.82c-.275.13-.576.198-.88.2V12l8.23-4.76c.175.308.268.656.27 1.01z" fill="currentColor"></path></svg> Dataset card </a><a class="tab-alternate active" href="/datasets/sanjaykz/Java-code/viewer/"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 12 12"><path fill="currentColor" d="M2.5 2h7a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1Zm0 2v2h3V4h-3Zm4 0v2h3V4h-3Zm-4 3v2h3V7h-3Zm4 0v2h3V7h-3Z"></path></svg> Data Studio </a><a class="tab-alternate" href="/datasets/sanjaykz/Java-code/tree/main"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path class="uim-tertiary" d="M21 19h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0-4h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0-8h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0 4h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2z" opacity=".5" fill="currentColor"></path><path class="uim-primary" d="M9 19a1 1 0 0 1-1-1V6a1 1 0 0 1 2 0v12a1 1 0 0 1-1 1zm-6-4.333a1 1 0 0 1-.64-1.769L3.438 12l-1.078-.898a1 1 0 0 1 1.28-1.538l2 1.667a1 1 0 0 1 0 1.538l-2 1.667a.999.999 0 0 1-.64.231z" fill="currentColor"></path></svg> <span class="xl:hidden">Files</span> <span class="hidden xl:inline">Files and versions</span> <span class="inline-block "><span class="contents"><div slot="anchor" class="shadow-purple-500/10 ml-2 inline-flex -translate-y-px items-center gap-0.5 rounded-md border bg-white px-1 py-0.5 align-middle text-xs font-semibold leading-none text-gray-800 shadow-sm dark:border-gray-700 dark:bg-gradient-to-b dark:from-gray-925 dark:to-gray-925 dark:text-gray-300"><svg class="size-3 " xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 12 12"><path fill-rule="evenodd" clip-rule="evenodd" d="M6.14 3.64 5.1 4.92 2.98 2.28h2.06l1.1 1.36Zm0 4.72-1.1 1.36H2.98l2.13-2.64 1.03 1.28Zm4.9 1.36L8.03 6l3-3.72H8.96L5.97 6l3 3.72h2.06Z" fill="#7875FF"></path><path d="M4.24 6 2.6 8.03.97 6 2.6 3.97 4.24 6Z" fill="#FF7F41" opacity="1"></path></svg> <span>xet</span> </div></span> </span> </a><a class="tab-alternate" href="/datasets/sanjaykz/Java-code/discussions"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path><path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path></svg> Community <div class="ml-1.5 flex h-4 min-w-[1rem] items-center justify-center rounded px-1 text-xs leading-none shadow-sm bg-black text-white dark:bg-gray-800 dark:text-gray-200">1</div> </a></div> </div></div></header> </div> <div class="flex flex-col w-full"><div class="flex h-full flex-1"> <div class="flex flex-1 flex-col overflow-hidden " style="height: calc(100vh - 48px)"><div class="flex flex-col overflow-hidden h-full "> <div class="flex flex-1 flex-col overflow-hidden "><div class="flex flex-1 flex-col overflow-hidden"><div class="flex min-h-0 flex-1"><div class="flex flex-1 flex-col overflow-hidden"><div class="md:shadow-xs dark:border-gray-800 md:my-4 md:ml-4 md:rounded-lg md:border flex min-w-0 flex-wrap "><div class="flex min-w-0 flex-1 flex-wrap"><div class="grid flex-1 grid-cols-1 overflow-hidden text-sm md:grid-cols-2 md:place-content-center md:rounded-l-lg"><label class="relative block flex-1 px-3 py-2 hover:bg-gray-50 dark:border-gray-850 dark:hover:bg-gray-900 md:border-r md:border-r-0 hidden" title="default"><span class="text-gray-500">Subset (1)</span> <div class="flex items-center whitespace-nowrap"><span class="truncate">default</span> <span class="mx-2 text-gray-500">·</span> <span class="text-gray-500">~438k rows (showing the first 346k)</span> <svg class="ml-auto min-w-6 pl-2" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg></div> <select class="absolute inset-0 z-10 w-full cursor-pointer border-0 bg-white text-base opacity-0"><optgroup label="Subset (1)"><option value="default" selected>default (~438k rows, showing the first 346k)</option></optgroup></select></label> <label class="relative block flex-1 px-3 py-2 hover:bg-gray-50 dark:border-gray-850 dark:hover:bg-gray-900 md:border-r md:border-r" title="train"><div class="text-gray-500">Split (1)</div> <div class="flex items-center overflow-hidden whitespace-nowrap"><span class="truncate">train</span> <span class="mx-2 text-gray-500">·</span> <span class="text-gray-500">~438k rows (showing the first 346k)</span> <svg class="ml-auto min-w-6 pl-2" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg></div> <select class="absolute inset-0 z-10 w-full cursor-pointer border-0 bg-white text-base opacity-0"><optgroup label="Split (1)"><option value="train" selected>train (~438k rows, showing the first 346k)</option></optgroup></select></label></div></div> <div class="hidden flex-none flex-col items-center gap-0.5 px-1 md:flex justify-end border-l"> <span class="inline-block "><span class="contents"><div slot="anchor"><button class="group text-gray-500 hover:text-gray-700" aria-label="Hide sidepanel"><div class="rounded-xs flex size-4 items-center justify-center border border-gray-400 bg-gray-100 hover:border-gray-600 hover:bg-blue-50 dark:border-gray-600 dark:bg-gray-800 dark:hover:bg-gray-700 dark:group-hover:border-gray-400"><div class="float-left h-full w-[65%]"></div> <div class="float-right h-full w-[35%] bg-gray-400 group-hover:bg-gray-600 dark:bg-gray-600 dark:group-hover:bg-gray-400"></div></div></button></div></span> </span> <div class="relative "> <button class="btn px-0.5 py-0.5 " type="button"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="p-0.5" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><circle cx="16" cy="7" r="3" fill="currentColor"></circle><circle cx="16" cy="16" r="3" fill="currentColor"></circle><circle cx="16" cy="25" r="3" fill="currentColor"></circle></svg> </button> </div></div></div> <div class="flex min-h-0 flex-1 flex-col border dark:border-gray-800 md:mb-4 md:ml-4 md:rounded-lg"> <div class="bg-linear-to-r text-smd relative flex items-center dark:border-gray-900 dark:bg-gray-950 false rounded-t-lg [&:has(:focus)]:from-gray-50 [&:has(:focus)]:to-transparent [&:has(:focus)]:to-20% dark:[&:has(:focus)]:from-gray-900"><form class="flex-1"><svg class="absolute left-3 top-1/2 transform -translate-y-1/2 pointer-events-none text-gray-400" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M30 28.59L22.45 21A11 11 0 1 0 21 22.45L28.59 30zM5 14a9 9 0 1 1 9 9a9 9 0 0 1-9-9z" fill="currentColor"></path></svg> <input disabled class="outline-hidden h-9 w-full border-none bg-transparent px-1 pl-9 pr-3 placeholder:text-gray-400 " placeholder="Search this dataset" dir="auto"></form> <div class="flex items-center gap-2 px-2 py-1"> <button type="button" class="hover:bg-yellow-200/70 flex items-center gap-1 rounded-md border border-yellow-200 bg-yellow-100 pl-0.5 pr-1 text-[.8rem] leading-normal text-gray-700 dark:border-orange-500/25 dark:bg-orange-500/20 dark:text-gray-300 dark:hover:brightness-110 md:hidden"><div class="rounded-sm bg-yellow-300 px-1 font-mono text-[.7rem] font-bold text-black dark:bg-yellow-700 dark:text-gray-200">SQL </div> Console </button></div></div> <div class="flex flex-1 flex-col overflow-hidden min-h-64 flex w-full flex-col border-t md:rounded-b-lg md:shadow-lg"> <div class="flex-1 relative overflow-auto"><table class="w-full table-auto rounded-lg font-mono text-xs text-gray-900"><thead class="shadow-xs sticky left-0 right-0 top-0 z-1 bg-white align-top"><tr class="space-y-54 h-full min-w-fit divide-x border-b text-left"><th class="h-full max-w-sm p-2 text-left relative w-full"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex min-w-0 items-center justify-between"><span class="min-w-0 truncate" title="answer">answer</span> <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">lengths</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="0" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="13.2" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="26.4" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="39.599999999999994" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="52.8" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="66" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="79.19999999999999" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="92.39999999999999" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="105.6" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g> <rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect> <rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect> <rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect> <rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect> <rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect> <rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect> <rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect> <rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect> <rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect> <rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">17</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">10.2M</div> </div></div></div></div> </th></tr></thead> <tbody class="h-16 overflow-scroll"><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1200"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.ovirt.engine.core.common.businessentities; import java.util.Map; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.errors.VdcBllErrors; import org.ovirt.engine.core.common.eventqueue.EventResult; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.TransactionScopeOption; public interface IVdsEventListener { void vdsNotResponding(VDS vds, boolean executeSshSoftFencing); // BLL void vdsNonOperational(Guid vdsId, NonOperationalReason type, boolean logCommand, boolean saveToDb, Guid domainId); // BLL void vdsNonOperational(Guid vdsId, NonOperationalReason type, boolean logCommand, boolean saveToDb, Guid domainId, Map<String, String> customLogValues); // BLL void vdsMovedToMaintenance(VDS vds); // BLL EventResult storageDomainNotOperational(Guid storageDomainId, Guid storagePoolId); // BLL EventResult masterDomainNotOperational(Guid storageDomainId, Guid storagePoolId, boolean isReconstructToInactiveDomains); // BLL void processOnVmStop(Guid vmId); boolean vdsUpEvent(VDS vds); void processOnClientIpChange(VDS vds, Guid vmId); void processOnCpuFlagsChange(Guid vdsId); void processOnVmPoweringUp(Guid vds_id, Guid vmid, String display_ip, int display_port); void handleVdsVersion(Guid vdsId); void rerun(Guid vmId); void runningSucceded(Guid vmId); void removeAsyncRunningCommand(Guid vmId); // void VdsNetworkConfigurationChanged(VDS vds); void storagePoolUpEvent(StoragePool storagePool, boolean isNewSpm); void storagePoolStatusChange(Guid storagePoolId, StoragePoolStatus status, AuditLogType auditLogType, VdcBllErrors error); void storagePoolStatusChange(Guid storagePoolId, StoragePoolStatus status, AuditLogType auditLogType, VdcBllErrors error, TransactionScopeOption transactionScopeOption); void storagePoolStatusChanged(Guid storagePoolId, StoragePoolStatus status); void runFailedAutoStartVM(Guid vmId); boolean restartVds(Guid vdsId); }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1201"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.ovirt.engine.core.extensions.mgr; import org.slf4j.Logger; import org.ovirt.engine.api.extensions.Base; import org.ovirt.engine.api.extensions.ExtMap; import org.ovirt.engine.api.extensions.Extension; public class ExtensionProxy implements Extension { private Extension proxied; private ExtMap context; private void dumpMap(String prefix, ExtMap map) { Logger logger = context.<Logger>get(ExtensionsManager.TRACE_LOG_CONTEXT_KEY); if (logger.isDebugEnabled()) { logger.debug(prefix + " BEGIN"); logger.debug(map.toString()); logger.debug(prefix + " END"); } } public ExtensionProxy(Extension proxied, ExtMap context) { this.proxied = proxied; this.context = context; } public Extension getExtension() { return proxied; } public ExtMap getContext() { return context; } @Override public void invoke(ExtMap input, ExtMap output) { input.putIfAbsent(Base.InvokeKeys.CONTEXT, context); dumpMap("Invoke Input", input); try { proxied.invoke(input, output); } catch (Throwable e) { output.mput( Base.InvokeKeys.RESULT, Base.InvokeResult.FAILED ).mput( Base.InvokeKeys.MESSAGE, String.format( "Exception: %s: %s", e.getClass(), e.getMessage() ) ).mput( ExtensionsManager.CAUSE_OUTPUT_KEY, e ); } dumpMap("Invoke Output", output); } public ExtMap invoke(ExtMap input, boolean allowUnsupported, boolean allowFail) { ExtMap output = new ExtMap(); invoke(input, output); String message = output.<String>get(Base.InvokeKeys.MESSAGE); switch(output.<Integer>get(Base.InvokeKeys.RESULT, Base.InvokeResult.FAILED)) { case Base.InvokeResult.SUCCESS: break; case Base.InvokeResult.UNSUPPORTED: if (!allowUnsupported) { throw new ExtensionInvokeCommandUnsupportedException( message == null ? "Unsupported command" : message, input, output ); } break; case Base.InvokeResult.FAILED: default: if (!allowFail) { throw new ExtensionInvokeCommandFailedException( message == null ? "Invoke failed" : message, input, output ); } break; } return output; } public ExtMap invoke(ExtMap input, boolean allowUnsupported) { return invoke(input, allowUnsupported, false); } public ExtMap invoke(ExtMap input) { return invoke(input, false, false); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1202"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package gov.nih.nci.cagrid.wsenum.utils; import gov.nih.nci.cagrid.common.Utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import javax.xml.namespace.QName; import javax.xml.soap.SOAPElement; import org.globus.ws.enumeration.EnumIterator; import org.globus.ws.enumeration.IterationConstraints; import org.globus.ws.enumeration.IterationResult; import org.globus.ws.enumeration.TimeoutException; import org.globus.wsrf.encoding.ObjectSerializer; import org.globus.wsrf.encoding.SerializationException; /** * PersistantSDKObjectIterator * Enumeration iterator which provides for persisting caCORE SDK objects to disk * * @author <A HREF="MAILTO:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="20455256494e60424d490e4f53550e454455">[email protected]</a>">David W. Ervin</A> * * @created Aug 17, 2006 * @version $Id$ */ public class SimplePersistantSDKObjectIterator implements EnumIterator { private static StringBuffer configFileContents = null; private File file = null; private BufferedReader fileReader = null; private QName objectQName = null; private boolean isReleased; private SimplePersistantSDKObjectIterator(File file, QName objectQName) throws FileNotFoundException { this.file = file; this.fileReader = new BufferedReader(new FileReader(file)); this.objectQName = objectQName; this.isReleased = false; } /** * Loads a wsdd config file for discovering type mappings needed to serialize / deserialize SDK objects * * @param filename * @throws Exception */ public static void loadWsddConfig(String filename) throws Exception { configFileContents = Utils.fileToStringBuffer(new File(filename)); } /** * Serializes a List of caCORE SDK generated objects to a temp file on * the local disk, then creates an EnumIterator which can return * those objects. * * @param objects * The list of caCORE SDK objects to be enumerated * @param objectQName * The QName of the objects * @return * @throws Exception */ public static EnumIterator createIterator(List objects, QName objectQName) throws Exception { return createIterator(objects, objectQName, File.createTempFile("EnumIteration", ".serialized").getAbsolutePath()); } /** * Serializes a List of caCORE SDK generated objects to a specified file on * the local disk, then creates an EnumIterator which can return * those objects. * * @param objects * The list of caCORE SDK objects to be enumerated * @param objectQName * The QName of the objects * @param filename * The name of the file to serialize objects into * @return * @throws Exception */ public static EnumIterator createIterator(List objects, QName objectQName, String filename) throws Exception { writeSdkObjects(objects, objectQName, filename); return new SimplePersistantSDKObjectIterator(new File(filename), objectQName); } /** * Writes the SDK serializable objects to disk * * @param objects * The list of objects to write out * @param name * The QName of the objects * @param filename * The filename to store the objects into * @throws Exception */ private static void writeSdkObjects(List objects, QName name, String filename) throws Exception { BufferedWriter fileWriter = new BufferedWriter(new FileWriter(filename)); Iterator objIter = objects.iterator(); while (objIter.hasNext()) { StringWriter writer = new StringWriter(); if (configFileContents != null) { Utils.serializeObject(objIter.next(), name, writer, new ByteArrayInputStream(configFileContents.toString().getBytes())); } else { Utils.serializeObject(objIter.next(), name, writer); } String xml = writer.toString().trim(); fileWriter.write(String.valueOf(xml.length()) + "\n"); fileWriter.write(xml); } fileWriter.flush(); fileWriter.close(); } /** * Retrieves the next set of items of the enumeration. * <b>Note:</b> This implementation ignores any iteration constraints except for max elements * * @param constraints the constrains for this iteration. Can be null. * If null, default constraints must be assumed. * @return the result of this iteration that fulfils the specified * constraints. It must always be non-null. * @throws TimeoutException if <tt>maxTime</tt> constraint was specified * and the enumeration data was not collected within that time. * <i>This is never thrown in this implementation</i> * @throws NoSuchElementException if iterator has no more elements */ public IterationResult next(IterationConstraints constraints) throws TimeoutException, NoSuchElementException { // check for release if (isReleased) { throw new NoSuchElementException("Enumeration has been released"); } // temporary list to hold SOAPElements List soapElements = new ArrayList(constraints.getMaxElements()); // start building results String xml = null; while (soapElements.size() < constraints.getMaxElements() && (xml = getNextXmlChunk()) != null) { try { SOAPElement element = ObjectSerializer.toSOAPElement(xml, objectQName); soapElements.add(element); } catch (SerializationException ex) { release(); NoSuchElementException nse = new NoSuchElementException("Error serializing element -- " + ex.getMessage()); nse.setStackTrace(ex.getStackTrace()); throw nse; } } // if the xml text is null, we're at the end of the iteration return wrapUpElements(soapElements, xml == null); } /** * Encapsulates converting the list of SOAPElements to an array, then an Iteration Result * * @param soapElements * @param end * @return */ private IterationResult wrapUpElements(List soapElements, boolean end) { SOAPElement[] elements = new SOAPElement[soapElements.size()]; soapElements.toArray(elements); return new IterationResult(elements, end); } /** * Reads the next chunk of XML from the file * * @return * Null if no more XML is found */ private String getNextXmlChunk() { try { String charCountStr = fileReader.readLine(); if (charCountStr != null) { int toRead = Integer.parseInt(charCountStr); char[] charBuff = new char[toRead]; int count = 0; int len = 0; while (count < toRead) { len = fileReader.read(charBuff, count, charBuff.length - count); count += len; } return new String(charBuff); } else { return null; } } catch (IOException ex) { ex.printStackTrace(); return null; } } /** * Releases the enumeration's resources. Specificaly, this deletes the underlying serialization file */ public void release() { try { fileReader.close(); } catch (Exception ex) { ex.printStackTrace(); } file.delete(); isReleased = true; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1203"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package de.rocketinternet.android.bucket.network; import android.content.Context; import android.net.Uri; import com.squareup.okhttp.Cache; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import org.json.JSONException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import de.rocketinternet.android.bucket.RocketBucket; import de.rocketinternet.android.bucket.models.Bucket; import de.rocketinternet.android.bucket.models.Experiment; /** * @author Sameh Gerges */ public class NetworkTask implements com.squareup.okhttp.Callback { private static String formSplitUrl(String endpoint, String deviceId) { return endpoint + "?user_id=" + deviceId; } private final String HTTP_HEADER_API_KEYE = "X-Api-Key"; private final String DIR_NAME_CACHING = "rocket_bucket"; private final int CACHE_SIZE = 1 * 1024 * 1024; // 1 MiB private final int MAX_RETRY_COUNT = 5; private static OkHttpClient client; private final Request request; private final NetworkTaskCallback callBack; private int trailsCount; public NetworkTask(Context context, String apiKey, String url, NetworkTaskCallback callBack) { this.callBack = callBack; if (client == null) { this.client = new OkHttpClient(); if (!RocketBucket.isDebug()) {//so we do not stuck with cached response while developing File cachingDir = new File(context.getCacheDir(), DIR_NAME_CACHING); if (cachingDir.exists() || cachingDir.mkdirs()) { this.client.setCache(new Cache(cachingDir, CACHE_SIZE)); } else { callBack.onFailure(new RuntimeException("RocketBucket: failed to create caching dir " + cachingDir.getAbsolutePath())); } } /*if (RocketBucket.isDebug()) { com.squareup.okhttp.logging.HttpLoggingInterceptor loggingInterceptor = new com.squareup.okhttp.logging.HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String s) { Log.d(RocketBucket.TAG, s); } }); loggingInterceptor.setLevel(com.squareup.okhttp.logging.HttpLoggingInterceptor.Level.BASIC); this.client.networkInterceptors().add(loggingInterceptor); }*/ } this.request = new Request.Builder() .url(url) .header(HTTP_HEADER_API_KEYE, apiKey).build(); client.newCall(this.request).enqueue(this); } @Override public void onFailure(Request request, IOException e) { trailsCount++; if (trailsCount < MAX_RETRY_COUNT) { client.newCall(request).enqueue(this); } callBack.onFailure(e); } @Override public void onResponse(com.squareup.okhttp.Response response) throws IOException { if (response.body() != null && response.isSuccessful()) { InputStream inputStream = null; try { inputStream = response.body().byteStream(); callBack.onSuccess(inputStream); } catch (Throwable t) { callBack.onFailure(t); } finally { if (inputStream != null) { inputStream.close(); } } } } private interface NetworkTaskCallback { void onSuccess(InputStream inputStream) throws IOException, JSONException; void onFailure(Throwable t); } public interface Callback<T> { void onCompletion(T response, Throwable error); } public static void updateLatestBucket(Context context, String endpoint, String apiKey, String deviceId, final Callback<Map<String, Bucket>> experimentMap) { new NetworkTask(context, apiKey, formSplitUrl(endpoint, deviceId), new NetworkTaskCallback() { @Override public void onSuccess(InputStream inputStream) throws IOException { experimentMap.onCompletion(JsonParser.parseExperiments(inputStream), null); } @Override public void onFailure(Throwable t) { experimentMap.onCompletion(null, t); } }); } public static void getAllBuckets(Context context, String endpoint, String apiKey, final Callback<List<Experiment>> experimentMap) { new NetworkTask(context, apiKey, buildAllBucketsEndUrl(endpoint), new NetworkTaskCallback() { @Override public void onSuccess(InputStream inputStream) throws IOException, JSONException { experimentMap.onCompletion(JsonParser.parseAllExperiments(inputStream), null); } @Override public void onFailure(Throwable t) { experimentMap.onCompletion(null, t); } }); } private static String buildAllBucketsEndUrl(String endpoint) { return Uri.parse(endpoint).buildUpon().appendPath("all").toString(); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1204"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package io.cattle.platform.systemstack.service; import static io.cattle.platform.core.model.tables.ProjectTemplateTable.*; import io.cattle.platform.archaius.util.ArchaiusUtil; import io.cattle.platform.async.utils.TimeoutException; import io.cattle.platform.core.dao.GenericResourceDao; import io.cattle.platform.core.model.ProjectTemplate; import io.cattle.platform.lock.LockCallbackWithException; import io.cattle.platform.lock.LockManager; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.object.process.ObjectProcessManager; import io.cattle.platform.systemstack.catalog.CatalogService; import io.cattle.platform.systemstack.lock.ProjectTemplateLoadLock; import io.cattle.platform.task.Task; import io.cattle.platform.util.exception.ExceptionUtils; import io.cattle.platform.util.type.InitializationTask; import io.github.ibuildthecloud.gdapi.condition.Condition; import io.github.ibuildthecloud.gdapi.condition.ConditionType; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import javax.inject.Inject; import javax.inject.Named; import org.apache.cloudstack.managed.context.NoExceptionRunnable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.config.DynamicBooleanProperty; public class ProjectTemplateService implements InitializationTask, Task { private static final DynamicBooleanProperty CATALOG_URL = ArchaiusUtil.getBoolean("catalog.url"); private static final DynamicBooleanProperty LAUNCH_CATALOG = ArchaiusUtil.getBoolean("catalog.execute"); private static final DynamicBooleanProperty DEFAULTS = ArchaiusUtil.getBoolean("project.template.defaults"); private static final Logger log = LoggerFactory.getLogger(ProjectTemplateService.class); @Inject CatalogService catalogService; @Inject @Named("CoreExecutorService") ExecutorService executor; @Inject ObjectManager objectManager; @Inject ObjectProcessManager processManager; @Inject GenericResourceDao resourceDao; @Inject LockManager lockManager; boolean initialRun = true; @Override public void start() { Runnable run = new NoExceptionRunnable() { @Override protected void doRun() throws Exception { while (true) { try { reload(); log.info("Loaded project templates from the catalog"); break; } catch (IOException e) { } Thread.sleep(1000); } } }; CATALOG_URL.addCallback(run); LAUNCH_CATALOG.addCallback(run); DEFAULTS.addCallback(run); executor.submit(run); } @Override public void run() { try { reload(); } catch (IOException e) { } catch (InterruptedException e) { } } protected void reload() throws IOException, InterruptedException { try { lockManager.tryLock(new ProjectTemplateLoadLock(), new LockCallbackWithException<Object, Exception>() { @Override public Object doWithLock() throws Exception { reloadWithLock(); return null; } }, Exception.class); } catch (Exception e) { ExceptionUtils.rethrow(e, InterruptedException.class); ExceptionUtils.rethrow(e, IOException.class); ExceptionUtils.rethrowRuntime(e); } } protected void reloadWithLock() throws IOException, InterruptedException { if (!LAUNCH_CATALOG.get() || !DEFAULTS.get()) { return; } List<ProjectTemplate> installedTemplates = objectManager.find(ProjectTemplate.class, PROJECT_TEMPLATE.IS_PUBLIC, true, PROJECT_TEMPLATE.REMOVED, null, PROJECT_TEMPLATE.EXTERNAL_ID, new Condition(ConditionType.LIKE, "catalog: Map<String, Map<Object, Object>> templatesToInstall = catalogService.getTemplates(installedTemplates); int i = 0; while (initialRun && templatesToInstall.size() == 0) { log.info("Waiting for project templates to load"); if (i++ > 120) { throw new TimeoutException("Waiting for project templates"); } Thread.sleep(2000); templatesToInstall = catalogService.getTemplates(installedTemplates); } for (ProjectTemplate installed : installedTemplates) { templatesToInstall.remove(installed.getExternalId()); } for (Map.Entry<String, Map<Object, Object>> entry : templatesToInstall.entrySet()) { Map<Object, Object> toInstall = entry.getValue(); toInstall.put(PROJECT_TEMPLATE.ACCOUNT_ID, null); toInstall.put(PROJECT_TEMPLATE.IS_PUBLIC, true); toInstall.put(PROJECT_TEMPLATE.EXTERNAL_ID, entry.getKey()); log.info("Adding project template [{}]", entry.getKey()); Map<String, Object> data = objectManager.convertToPropertiesFor(ProjectTemplate.class, toInstall); resourceDao.createAndSchedule(ProjectTemplate.class, data); } initialRun = false; } @Override public String getName() { return "project.template.reload"; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1205"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.openforis.collect.earth.app.service; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.annotation.PostConstruct; import org.apache.commons.dbcp.BasicDataSource; import org.openforis.collect.earth.app.EarthConstants; import org.openforis.collect.earth.core.utils.CsvReaderUtils; import org.openforis.idm.metamodel.Schema; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import au.com.bytecode.opencsv.CSVReader; @Component public class RegionCalculationUtils { private static final String SHRUB_COUNT = "shrub_count"; private static final String TREE_COUNT = "tree_count"; private static final String REGION_AREAS_CSV = "region_areas.csv"; //$NON-NLS-1$ private static final String ATTRIBUTE_AREAS_CSV = "areas_per_attribute.csv"; //$NON-NLS-1$ private static final String PLOT_WEIGHT = "plot_weight"; //$NON-NLS-1$ private static final String EXPANSION_FACTOR = "expansion_factor"; //$NON-NLS-1$ private static final String TREES_PER_EXP_FACTOR = "trees_per_expansion_factor"; //$NON-NLS-1$ private static final String SHRUBS_PER_EXP_FACTOR = "shrubs_per_expansion_factor"; //$NON-NLS-1$ private final Logger logger = LoggerFactory.getLogger(RegionCalculationUtils.class); private static final String NO_DATA_LAND_USE = "noData"; //$NON-NLS-1$ @Autowired EarthSurveyService earthSurveyService; @Autowired LocalPropertiesService localPropertiesService; @Autowired private BasicDataSource rdbDataSource; @Autowired private SchemaService schemaService; private JdbcTemplate jdbcTemplate; @PostConstruct public void initialize() { jdbcTemplate = new JdbcTemplate(rdbDataSource); } public void handleRegionCalculation(){ try { createWeightFactors(); // If the region_areas.csv is not present then try to add the areas "per attribute" using the file areas_per_attribute.csv boolean areasAdded = false; if(!addAreasPerRegion()){ if( addAreasPerAttribute() ){ areasAdded = true; } }else{ areasAdded = true; } if( areasAdded ){ handleNumberOfTrees(); handleNumberOfShrubs(); recalculatePlotWeights(); } } catch (Exception e) { logger.error( "Error when calculating the expansion factors for the plots ", e); } } private void recalculatePlotWeights() { String schemaName = schemaService.getSchemaPrefix(); List<Double> distinctExpFactors = jdbcTemplate.queryForList("SELECT DISTINCT(" + EXPANSION_FACTOR + ") FROM " + schemaName + "plot", Double.class); ArrayList<Double> actualExpFactors = new ArrayList<Double>(); for (Object expFactor : distinctExpFactors) { if( expFactor!= null ){ actualExpFactors.add( (Double) expFactor ); } } // Sort in ascending order Collections.sort(actualExpFactors); double minimunEF = actualExpFactors.get(0); for (double expansionFactor : actualExpFactors) { // The plots with the minimum expansion factor will have a weight of 1 double plotWeight = expansionFactor/minimunEF; final Object[] updateValues = new Object[2]; updateValues[0] = plotWeight; updateValues[1] = expansionFactor; jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+PLOT_WEIGHT+"=? WHERE " + EXPANSION_FACTOR +" =?", updateValues); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } } private void createWeightFactors(){ final String schemaName = schemaService.getSchemaPrefix(); jdbcTemplate.execute("ALTER TABLE " + schemaName + "plot ADD " + EXPANSION_FACTOR + " FLOAT"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ jdbcTemplate.execute("ALTER TABLE " + schemaName + "plot ADD " + PLOT_WEIGHT + " FLOAT"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /** * This is the "old way"of assigning an expansion factor (the area in hecaters that a plot represents) to a plot based on the information form the "region_areas.csv" file. * @return True if there was a region_areas.csv file, false if not present so that areas were not assigned. * @throws SQLException */ private boolean addAreasPerRegion() throws SQLException { final File regionAreas = new File( localPropertiesService.getProjectFolder() + File.separatorChar + REGION_AREAS_CSV); String schemaName = schemaService.getSchemaPrefix(); if (regionAreas.exists()) { try { CSVReader csvReader = CsvReaderUtils.getCsvReader(regionAreas.getAbsolutePath()); String[] csvLine = null; while( ( csvLine = csvReader.readNext() ) != null ){ try { String region = csvLine[0]; String plot_file = csvLine[1]; int area_hectars = Integer.parseInt( csvLine[2] ); final Float plot_weight = Float.parseFloat( csvLine[3] ); Object[] parameters = new String[]{region,plot_file}; Integer plots_per_region = jdbcTemplate.queryForObject( "SELECT count( DISTINCT "+EarthConstants.PLOT_ID+") FROM " + schemaName + "plot WHERE ( region=? OR plot_file=? ) AND land_use_category != '"+NO_DATA_LAND_USE+"' ", parameters,Integer.class); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ Float expansion_factor_hectars_calc = 0f; if( plots_per_region.intValue() != 0 ){ expansion_factor_hectars_calc = (float)area_hectars / (float) plots_per_region.intValue(); } final Object[] updateValues = new Object[4]; updateValues[0] = expansion_factor_hectars_calc; updateValues[1] = plot_weight; updateValues[2] = region; updateValues[3] = plot_file; jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+EXPANSION_FACTOR+"=?, "+PLOT_WEIGHT+"=? WHERE region=? OR plot_file=?", updateValues); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } catch (NumberFormatException e) { logger.error("Possibly the header", e); //$NON-NLS-1$ } } // FINALLY ASSIGN A WEIGHT OF CERO AND AN EXPANSION FACTOR OF 0 FOR THE PLOTS WITH NO_DATA final Object[] updateNoDataValues = new Object[3]; updateNoDataValues[0] = 0; updateNoDataValues[1] = 0; updateNoDataValues[2] = NO_DATA_LAND_USE; jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+EXPANSION_FACTOR+"=?, "+PLOT_WEIGHT+"=? WHERE land_use_category=?", updateNoDataValues); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } catch (FileNotFoundException e) { logger.error("File not found?", e); //$NON-NLS-1$ } catch (IOException e) { logger.error("Error reading the CSV file", e); //$NON-NLS-1$ } return true; }else{ logger.warn("No CSV region_areas.csv present, calculating areas will not be possible"); //$NON-NLS-1$ return false; } } private void handleNumberOfShrubs() { String schemaName = schemaService.getSchemaPrefix(); // This is specific to the Global Forest Survey - Drylands monitoring assessment if( AnalysisSaikuService.surveyContains(SHRUB_COUNT, earthSurveyService.getCollectSurvey() ) ){ // First set the number of shrubs to 30 if the user assessed that there were more than 30 shrubs on the plot // This way we get a conservative estimation jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+SHRUB_COUNT+"=30 WHERE many_shrubs=1"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ jdbcTemplate.execute("ALTER TABLE " + schemaName + "plot ADD " + SHRUBS_PER_EXP_FACTOR + " FLOAT"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+SHRUBS_PER_EXP_FACTOR+"="+EXPANSION_FACTOR+"*2*" + SHRUB_COUNT); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } } private void handleNumberOfTrees() { String schemaName = schemaService.getSchemaPrefix(); // This is specific to the Global Forest Survey - Drylands monitoring assessment if( AnalysisSaikuService.surveyContains(TREE_COUNT, earthSurveyService.getCollectSurvey() ) ){ // First set the number of shrubs to 30 if the user assessed that there were more than 30 shrubs on the plot // This way we get a conservative estimation jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+TREE_COUNT+"=30 WHERE many_trees=1"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ jdbcTemplate.execute("ALTER TABLE " + schemaName + "plot ADD " + TREES_PER_EXP_FACTOR + " FLOAT"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+TREES_PER_EXP_FACTOR+"="+EXPANSION_FACTOR+"*2*" + TREE_COUNT); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } } private boolean addAreasPerAttribute() throws SQLException { final File areasPerAttribute = new File( localPropertiesService.getProjectFolder() + File.separatorChar + ATTRIBUTE_AREAS_CSV); String schemaName = schemaService.getSchemaPrefix(); if (areasPerAttribute.exists()) { try { CSVReader csvReader = CsvReaderUtils.getCsvReader(areasPerAttribute.getAbsolutePath()); String[] csvLine = null; // The header (first line) should contain the names of the three columns : attribute_name,area,weight String[] columnNames = csvReader.readNext(); ArrayList<String> attributeNames = new ArrayList<String>(); if(columnNames.length < 3 ){ throw new RuntimeException("The " + areasPerAttribute.getAbsolutePath() + " file needs have this format : attribute_name1,attribute_name2,...attribute_nameN,area,weight./nAt least one attribute is necessary. This wuuld be the attribute or attributes (their name in the survey definition) that would realte the plot with its expancion factor"); } for( int colPosition = 0; colPosition<columnNames.length -2; colPosition++){ String attributeName = columnNames[colPosition]; // Validate attribute name if( !isAttributeInPlotEntity( attributeName ) ){ throw new RuntimeException("The expected format of the CSV file at " + areasPerAttribute.getAbsolutePath() + " should be attribute_name,area,weight. The name of the attribute in hte first column of your CSV '" + attributeName + "'is not a attribute under the plot entity."); } attributeNames.add(attributeName); } //Validate area and weight headers. if( !columnNames[ columnNames.length -2 ].equalsIgnoreCase("area") || !columnNames[columnNames.length -1].equalsIgnoreCase("weight")){ throw new RuntimeException("The expected format of the CSV file at " + areasPerAttribute.getAbsolutePath() + " should be attribute_name,area,weight"); } int line = 1; while( ( csvLine = csvReader.readNext() ) != null ){ try{ int area_hectars = Integer.parseInt( csvLine[columnNames.length -2] ); final Float plot_weight = Float.parseFloat( csvLine[columnNames.length -1] ); int numberOfAttributes = attributeNames.size(); ArrayList<Object> attributeValues = new ArrayList<Object>(); for(int attributeValueCol = 0; attributeValueCol<numberOfAttributes;attributeValueCol++){ attributeValues.add(csvLine[attributeValueCol]); } StringBuffer selectQuery = new StringBuffer(); selectQuery.append("SELECT count( DISTINCT ").append(EarthConstants.PLOT_ID).append(") FROM ").append(schemaName).append("plot WHERE "); for (int attr =0; attr<attributeNames.size() ; attr++) { String attributeName = attributeNames.get(attr); selectQuery.append(attributeName); if( attr == numberOfAttributes-1 ){ selectQuery.append("=? "); }else{ selectQuery.append("=? AND "); } } Integer plots_per_region = jdbcTemplate.queryForObject(selectQuery.toString(), attributeValues.toArray(), Integer.class); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ // Calculate the expansion factor. Simply the deivision of the area for the selected attributes by the amount of plots that match the attribute values Float expansion_factor_hectars_calc = 0f; if( plots_per_region.intValue() != 0 ){ expansion_factor_hectars_calc = (float)area_hectars / (float) plots_per_region.intValue(); } // Build the update query StringBuffer updateQuery = new StringBuffer(); updateQuery.append("UPDATE ").append(schemaName).append("plot SET ").append(EXPANSION_FACTOR).append("=?, ").append(PLOT_WEIGHT).append("=? WHERE "); for (int attr =0; attr<attributeNames.size() ; attr++) { String attributeName = attributeNames.get(attr); updateQuery.append(attributeName); if( attr == numberOfAttributes-1 ){ updateQuery.append("=? "); }else{ updateQuery.append("=? AND "); } } // Add the expansion factor and plot_weight to the values that will be sent with the update attributeValues.add(0, expansion_factor_hectars_calc); attributeValues.add(1, plot_weight); jdbcTemplate.update(updateQuery.toString(), attributeValues.toArray()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ }catch( Exception e5){ logger.error("Problem in line number " + line + " with values " + Arrays.toString( csvLine ), e5 ); }finally{ line++; } } } catch (FileNotFoundException e) { logger.error("File not found?", e); //$NON-NLS-1$ } catch (IOException e) { logger.error("Error reading the CSV file", e); //$NON-NLS-1$ } return true; }else{ logger.warn("No CSV region_areas.csv present, calculating areas will not be possible"); //$NON-NLS-1$ return false; } } private boolean isAttributeInPlotEntity(String attributeName) { Schema schema = earthSurveyService.getCollectSurvey().getSchema(); boolean attributeExists = true; try { schema.getRootEntityDefinition(EarthConstants.ROOT_ENTITY_NAME ).getChildDefinition(attributeName); } catch (Exception e) { // The attribute does not exist under the plot entity attributeExists = false; } return attributeExists; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1206"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// CloudCoder - a web-based pedagogical programming environment // This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the package org.cloudcoder.builder2.server; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.cloudcoder.builder2.csandbox.EasySandboxSharedLibrary; import org.cloudcoder.builder2.javasandbox.JVMKillableTaskManager; import org.cloudcoder.builder2.pythonfunction.PythonKillableTaskManager; import org.cloudcoder.daemon.IDaemon; import org.cloudcoder.daemon.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of {@link IDaemon} to start, control, and shutdown * a Builder instance. * * @author David Hovemeyer */ public class Builder2Daemon implements IDaemon { private Logger logger = LoggerFactory.getLogger(this.getClass()); private List<BuilderAndThread> builderAndThreadList; private static class BuilderAndThread { final Builder2Server builder; final Thread thread; public BuilderAndThread(Builder2Server builder, Thread thread) { this.builder = builder; this.thread = thread; } } static class Options { private Properties config; public Options(Properties config) { this.config = config; } // The default property values are appropriate for running interactively for development. public String getAppHost() { return config.getProperty("cloudcoder.submitsvc.oop.host", "localhost"); } public int getAppPort() { return Integer.parseInt(config.getProperty("cloudcoder.submitsvc.oop.port", "47374")); } public int getNumThreads() { return Integer.parseInt(config.getProperty("cloudcoder.submitsvc.oop.numThreads", "2")); } public String getKeystoreFilename() { return config.getProperty("cloudcoder.submitsvc.ssl.keystore", "defaultkeystore.jks"); } public String getKeystorePassword() { return config.getProperty("cloudcoder.submitsvc.ssl.keystore.password", "changeit"); } } /* (non-Javadoc) * @see org.cloudcoder.daemon.IDaemon#start(java.lang.String) */ @Override public void start(String instanceName) { // If embedded configuration properties exist, read them Properties config; try { String configPropPath = "cloudcoder.properties"; ClassLoader clsLoader = this.getClass().getClassLoader(); config = Util.loadPropertiesFromResource(clsLoader, configPropPath); } catch (IllegalStateException e) { logger.warn("Could not load cloudcoder.properties, using default config properties"); config = new Properties(); } Options options = new Options(config); // Create the WebappSocketFactory which the builder tasks can use to create // connections to the webapp. WebappSocketFactory webappSocketFactory; try { webappSocketFactory = new WebappSocketFactory( options.getAppHost(), options.getAppPort(), options.getKeystoreFilename(), options.getKeystorePassword()); } catch (Exception e) { logger.error("Could not create WebappSocketFactory", e); throw new IllegalStateException("Could not create WebappSocketFactory", e); } // Install KillableTaskManager's security manager JVMKillableTaskManager.installSecurityManager(); PythonKillableTaskManager.installSecurityManager(); logger.info("Builder starting"); logger.info("appHost={}", options.getAppHost()); logger.info("appPort={}", options.getAppPort()); logger.info("numThreads={}", options.getNumThreads()); // Start Builder threads this.builderAndThreadList = new ArrayList<BuilderAndThread>(); for (int i = 0; i < options.getNumThreads(); i++) { Builder2Server builder_ = new Builder2Server(webappSocketFactory); Thread thread_ = new Thread(builder_); BuilderAndThread builderAndThread = new BuilderAndThread(builder_, thread_); builderAndThreadList.add(builderAndThread); builderAndThread.thread.start(); } } /* (non-Javadoc) * @see org.cloudcoder.daemon.IDaemon#handleCommand(java.lang.String) */ @Override public void handleCommand(String command) { // Right now the Builder has no runtime configuration commands logger.warn("Builder received unknown command " + command); } /* (non-Javadoc) * @see org.cloudcoder.daemon.IDaemon#shutdown() */ @Override public void shutdown() { // Shut down all Builder threads for (BuilderAndThread builderAndThread : builderAndThreadList) { try { builderAndThread.builder.shutdown(); builderAndThread.thread.join(); logger.info("Finished"); } catch (InterruptedException e) { e.printStackTrace(); } } // Ensure that if the EasySandbox shared library was built, // that its directory is deleted before the daemon exits. EasySandboxSharedLibrary.getInstance().cleanup(); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1207"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.glob3.mobile.generated; public class MarkEffectTarget implements EffectTarget { public void dispose() { } //C++ TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java: //#if ! C_CODE public final void unusedMethod() { } //#endif }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1208"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.glob3.mobile.generated; public class TileVisitorCache implements ITileVisitor { private MultiLayerTileTexturizer _texturizer; private final TilesRenderParameters _parameters; private final G3MRenderContext _rc; private final LayerSet _layerSet; public TileVisitorCache(MultiLayerTileTexturizer texturizer, TilesRenderParameters parameters, G3MRenderContext rc, LayerSet layerSet) { _texturizer = texturizer; _parameters = parameters; _rc = rc; _layerSet = layerSet; } public void dispose() { } //C++ TO JAVA CONVERTER WARNING: 'const' methods are not available in Java: //ORIGINAL LINE: void visitTile(Tile* tile) const public final void visitTile(Tile tile) { TileTextureBuilder ttb = new TileTextureBuilder(_texturizer, _rc, _layerSet, _parameters, _rc.getDownloader(), tile, null, null); ttb.start(); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1209"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package fr.masciulli.drinks.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SearchView; import android.widget.TextView; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnItemClick; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; import fr.masciulli.drinks.R; import fr.masciulli.drinks.activity.DrinkDetailActivity; import fr.masciulli.drinks.activity.MainActivity; import fr.masciulli.drinks.adapter.DrinksListAdapter; import fr.masciulli.drinks.data.DrinksProvider; import fr.masciulli.drinks.model.Drink; import fr.masciulli.drinks.view.ViewPagerScrollListener; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class DrinksListFragment extends Fragment implements Callback<List<Drink>>, ViewPagerScrollListener, SearchView.OnQueryTextListener { private static final String STATE_LIST = "drinks_list"; @InjectView(R.id.list) ListView mListView; @InjectView(R.id.progressbar) ProgressBar mProgressBar; @InjectView(android.R.id.empty) View mEmptyView; private DrinksListAdapter mListAdapter; private boolean mLoadingError = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); final View root = inflater.inflate(R.layout.fragment_drinks_list, container, false); ButterKnife.inject(this, root); mListView.setEmptyView(mEmptyView); mListAdapter = new DrinksListAdapter(getActivity()); mListView.setAdapter(mListAdapter); if (savedInstanceState != null) { if (savedInstanceState.containsKey(STATE_LIST)) { List<Drink> savedDrinks = savedInstanceState.getParcelableArrayList(STATE_LIST); mListAdapter.update(savedDrinks); } else { refresh(); } } else { refresh(); } return root; } @OnItemClick(R.id.list) public void openDrinkDetail(View view, int position) { Drink drink = mListAdapter.getItem(position); // Data needed for animations in sub activity int[] screenLocation = new int[2]; view.getLocationOnScreen(screenLocation); int orientation = getResources().getConfiguration().orientation; Intent intent = new Intent(getActivity(), DrinkDetailActivity.class); intent. putExtra("drink_name", drink.name). putExtra("drink_imageurl", drink.imageUrl). putExtra("drink_id", drink.id). putExtra("top", screenLocation[1]). putExtra("height", view.getHeight()). putExtra("orientation", orientation); startActivity(intent); if (!getResources().getBoolean(R.bool.dualpane)) { getActivity().overridePendingTransition(0, 0); } } @Override public void success(List<Drink> drinks, Response response) { mLoadingError = false; if (getActivity() == null) return; mListView.setVisibility(View.VISIBLE); mEmptyView.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.GONE); mListAdapter.update(drinks); } @Override public void failure(RetrofitError retrofitError) { mLoadingError = true; if (getActivity() == null) return; mProgressBar.setVisibility(View.GONE); mEmptyView.setVisibility(View.VISIBLE); ((MainActivity) getActivity()).setRefreshActionVisible(true); if (retrofitError.isNetworkError()) { Crouton.makeText(getActivity(), getString(R.string.network_error), Style.ALERT).show(); } else { Crouton.makeText(getActivity(), getString(R.string.list_loading_failed), Style.ALERT).show(); } } @Override public void onScroll(int position, float positionOffset, int positionOffsetPixels) { int first = mListView.getFirstVisiblePosition(); int last = mListView.getLastVisiblePosition(); for (int i = 0; i <= last - first; i++) { View itemRoot = mListView.getChildAt(i); if (itemRoot == null) continue; TextView nameView = (TextView) itemRoot.findViewById(R.id.name); // TODO get screenWidth somewhere else (always the same) int screenWidth = itemRoot.getWidth(); int textWidth = nameView.getWidth(); nameView.setRight(Math.round(screenWidth + positionOffset * textWidth)); nameView.setLeft(Math.round(screenWidth - textWidth + positionOffset * textWidth)); } } private void refresh() { mProgressBar.setVisibility(View.VISIBLE); mEmptyView.setVisibility(View.GONE); ((MainActivity) getActivity()).setRefreshActionVisible(false); DrinksProvider.getAllDrinks(this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.drinks_list, menu); // SearchView configuration final MenuItem searchMenuItem = menu.findItem(R.id.search); if (mLoadingError) { ((MainActivity) getActivity()).setRefreshActionVisible(true); } SearchView searchView = (SearchView) searchMenuItem.getActionView(); searchView.setQueryHint(getString(R.string.search_hint)); searchView.setOnQueryTextListener(this); } @Override public boolean onQueryTextSubmit(String s) { return false; } @Override public boolean onQueryTextChange(String s) { if (mListView != null) { mListAdapter.getFilter().filter(s); } return true; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mListAdapter.getCount() > 0) { outState.putParcelableArrayList(STATE_LIST, mListAdapter.getDrinks()); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.retry: refresh(); return true; } return super.onOptionsItemSelected(item); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1210"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.example.bot.spring; import java.util.Arrays; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import lombok.extern.slf4j.Slf4j; // The following code contains a bug in it. You need to fix it in Lab 2 in // order to make it work. // After you fix the code, the bot should be able to response based on // database.txt located in // sample-spring-boot-kitchensink/resources/static/database.txt. // This file contains a few lines with the format <input>:<output>. // The program below wish to perform an exact word match the input text // against the <input> against each line. The bot should replys // "XXX says <output>" // For instance, if the client sends "abc", the bot should reply // "kevinw says def" // If you registered your ITSC login as kevinw. @Slf4j public class DatabaseEngine { String search(String text) throws Exception { String result = null; BufferedReader br = null; InputStreamReader isr = null; try { isr = new InputStreamReader( this.getClass().getResourceAsStream(FILENAME)); br = new BufferedReader(isr); String sCurrentLine; while (result == null && (sCurrentLine = br.readLine()) != null) { String[] parts = sCurrentLine.split(":"); if (text.toLowerCase().equals(parts[0].toLowerCase())) { result = parts[1]; } } } catch (IOException e) { log.info("IOException while reading file: {}", e.toString()); } finally { try { if (br != null) br.close(); if (isr != null) isr.close(); } catch (IOException ex) { log.info("IOException while closing file: {}", ex.toString()); } } if (result != null) return result; throw new Exception("NOT FOUND"); } private final String FILENAME = "/static/database.txt"; }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1211"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.springframework.beans.factory.access; import java.lang.reflect.Method; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * A bean-factory post processor configured to trigger the instantiation and * configuration of a global service locator from a Spring application context. * <p> * <p> * This allows for the locator and the services it provides access to to be * configured via Spring just like any other bean. In addition, as a * <code>BeanFactoryPostProcessor</code> this class ensures locators are * instantiated before the objects that use them. This is often necessary when * objects access the locator through a convenient static accessors (e.g. * getInstance()), as opposed to having a reference to the locator injected * through a setter or constructor. * <p> * <p> * There are two different ways to load a singleton service locator: * <ol> * <li>By specifying one or more bean id references in the application context * that point to locators with static load() methods. In this case, the load() * method is called directly on the locator instance to configure the singleton * instance. For example: * * <pre> * &lt;bean id=&quot;serviceLocatorLoader&quot; * class=&quot;com.csi.commons.utils.beans.SingletonServiceLocatorLoader&quot;&gt; * &lt;constructor-arg index=&quot;0&quot;&gt; * &lt;listgt; * &lt;value&gt;consoleServices&lt;/value&gt; * &lt;/list&gt; * &lt;/constructor-arg&gt; * &lt;/bean&gt; * </pre> * * ... will call the static <code>load</code> method on the * <code>ConsoleServices</code> class, passing in the configured * <code>consoleServices</code> bean. * * <li>By specifying one or more singleton locator accessor classes with the * bean ID that corresponds to the instance to be loaded and shared. In this * case, load is called on the singleton locator accessor, and not the locator * itself. This approach completely abstracts away singleton status from the * locator class. As an example: * </ol> * * <pre> * &lt;bean id=&quot;serviceLocatorLoader&quot; * class=&quot;com.csi.commons.utils.beans.SingletonServiceLocatorLoader&quot;&gt; * &lt;constructor-arg index=&quot;0&quot;&gt; * &lt;listgt; * &lt;value&gt;<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e0d01001d01020b3d0b1c18070d0b1d2e0d0103400f0d030b402d01001d01020b3d0b1c18070d0b1d3d070009020b1a010022010d0f1a011c">[email protected]</a>&lt;/value&gt; * &lt;/list&gt; * &lt;/constructor-arg&gt; * &lt;/bean&gt; * </pre> * * ... will call the static <code>load</code> method on the * <code>ConsoleServicesSingletonLocator</code> class, passing in the * configured <code>consoleServices</code> bean. * * Note - take care not to abuse this pattern. Generally dependency * injection/IoC should be preferred to singleton, getInstance() style lookup. * * @author Keith Donald */ public class SingletonServiceLocatorLoader implements BeanFactoryPostProcessor { private static final Log logger = LogFactory .getLog(SingletonServiceLocatorLoader.class); public String[] locatorBeanIds; private String loadMethodName = "load"; private static final char CLASS_SEPARATOR = '@'; /** * Creates a SingletonServiceLocatorLoader that loads the specified services * using a static <code>load</code> method. * * @param beanIds * The configured service locator bean ids. */ public SingletonServiceLocatorLoader(String[] beanIds) { Assert.hasElements(beanIds); this.locatorBeanIds = beanIds; } /** * Set the name of the static load method to call to configure locators * with the shared bean instance. * * @param loadMethodName * The load method name, <code>load</code> is used by default. */ public void setLoadMethodName(String loadMethodName) { Assert.notNull(loadMethodName); this.loadMethodName = loadMethodName; } /** * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory */ public void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory) throws BeansException { for (int i = 0; i < locatorBeanIds.length; i++) { logger .info("Instantating locator bean '" + locatorBeanIds[i] + "'"); String locatorBeanId = locatorBeanIds[i]; Object locatorInstance = null; Class globalLocatorClass = null; int classSep = locatorBeanId.indexOf(CLASS_SEPARATOR); if (classSep == -1) { // no class specified, use locator class to load singleton // instance locatorInstance = beanFactory.getBean(locatorBeanIds[i]); globalLocatorClass = locatorInstance.getClass(); } else { // singleton class specified, use it to load shared instance try { locatorInstance = beanFactory.getBean(locatorBeanId .substring(0, classSep)); globalLocatorClass = Class.forName(locatorBeanId .substring(classSep + 1)); } catch (ClassNotFoundException e) { logger.warn("No class found '" + locatorBeanId.substring(0, classSep) + "'"); logger .warn("The singleton locator expression must be in the form <sharedBeanIdToLoad@singletonServiceLocatorAccessorClassName>"); } } if (locatorInstance == null || globalLocatorClass == null) { return; } Method loadMethod = getStaticLoadMethod(globalLocatorClass, locatorInstance); if (loadMethod == null) { logger .warn("No public static 'load' method found on singleton service locator '" + globalLocatorClass + "'"); } try { loadMethod.invoke(null, new Object[] { locatorInstance }); } catch (Exception e) { logger.warn("Unable to load locator '" + locatorInstance + "'", e); } } } private Method getStaticLoadMethod(Class globalLocatorClass, Object instance) { Class[] args = new Class[] { instance.getClass() }; Method method = ClassUtils.getStaticMethod(loadMethodName, globalLocatorClass, args); if (method == null) { Class[] interfaces = instance.getClass().getInterfaces(); for (int i = 0; i < interfaces.length; i++) { args[0] = interfaces[i]; method = ClassUtils.getStaticMethod(loadMethodName, globalLocatorClass, args); if (method != null) { break; } } } return method; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1212"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package gov.nih.nci.codegen.util; import gov.nih.nci.codegen.GenerationException; import gov.nih.nci.codegen.validator.ValidatorAttribute; import gov.nih.nci.codegen.validator.ValidatorClass; import gov.nih.nci.codegen.validator.ValidatorModel; import gov.nih.nci.ncicb.xmiinout.domain.UMLAssociation; import gov.nih.nci.ncicb.xmiinout.domain.UMLAssociationEnd; import gov.nih.nci.ncicb.xmiinout.domain.UMLAttribute; import gov.nih.nci.ncicb.xmiinout.domain.UMLClass; import gov.nih.nci.ncicb.xmiinout.domain.UMLDatatype; import gov.nih.nci.ncicb.xmiinout.domain.UMLDependency; import gov.nih.nci.ncicb.xmiinout.domain.UMLGeneralization; import gov.nih.nci.ncicb.xmiinout.domain.UMLInterface; import gov.nih.nci.ncicb.xmiinout.domain.UMLModel; import gov.nih.nci.ncicb.xmiinout.domain.UMLPackage; import gov.nih.nci.ncicb.xmiinout.domain.UMLTaggableElement; import gov.nih.nci.ncicb.xmiinout.domain.UMLTaggedValue; import gov.nih.nci.ncicb.xmiinout.domain.bean.UMLAssociationEndBean; import gov.nih.nci.ncicb.xmiinout.util.ModelUtil; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.jdom.Element; import gov.nih.nci.iso21090.hibernate.node.*; public class TransformerUtils { private static Logger log = Logger.getLogger(TransformerUtils.class); private String BASE_PKG_LOGICAL_MODEL; private String BASE_PKG_DATA_MODEL; private String INCLUDE_PACKAGE; private String EXCLUDE_PACKAGE; private String EXCLUDE_NAME; private String EXCLUDE_NAMESPACE; private String IDENTITY_GENERATOR_TAG; private Set<String> INCLUDE_PACKAGE_PATTERNS = new HashSet<String>(); private Set<String> EXCLUDE_PACKAGE_PATTERNS = new HashSet<String>(); private Set<String> EXCLUDE_CLASS_PATTERNS = new HashSet<String>(); private Set<String> EXCLUDE_NAMESPACE_PATTERNS = new HashSet<String>(); private String DATABASE_TYPE; private Map<String,String> CASCADE_STYLES = new HashMap<String,String>(); private ValidatorModel vModel; private ValidatorModel vModelExtension; private String namespaceUriPrefix; private boolean useGMETags = false; private boolean isJaxbEnabled = false; private boolean isISO21090Enabled = false; private UMLPackage isoDataTypeRootPackage; /** * UMLModel from which the code is to be generated */ private UMLModel model; public static final String TV_ID_ATTR_COLUMN = "id-attribute"; public static final String TV_MAPPED_ATTR_COLUMN = "mapped-attributes"; public static final String TV_MAPPED_ATTR_CONSTANT = "mapped-constant"; public static final String TV_ASSOC_COLUMN = "implements-association"; public static final String TV_INVERSE_ASSOC_COLUMN = "inverse-of"; public static final String TV_DISCR_COLUMN = "discriminator"; public static final String TV_CORRELATION_TABLE = "correlation-table"; public static final String TV_DOCUMENTATION = "documentation"; public static final String TV_DESCRIPTION = "description"; public static final String TV_LAZY_LOAD = "lazy-load"; public static final String TV_TYPE="type"; public static final String TV_MAPPED_COLLECTION_TABLE = "mapped-collection-table"; public static final String TV_MAPPED_ELEMENT_COLUMN = "mapped-element"; public static final String TV_CADSR_PUBLICID = "CADSR_ConceptualDomainPublicID"; public static final String TV_CADSR_VERSION = "CADSR_ConceptualDomainVersion"; public static final String TV_NCI_CASCADE_ASSOCIATION = "NCI_CASCADE_ASSOCIATION"; public static final String TV_NCI_EAGER_LOAD = "NCI_EAGER_LOAD"; public static final String TV_PK_GENERATOR = "NCI_GENERATOR."; public static final String TV_PK_GENERATOR_PROPERTY = "NCI_GENERATOR_PROPERTY"; public static final String TV_MAPPED_COLLECTION_ELEMENT_TYPE = "mapped-collection-element-type"; public static final String TV_NCI_GME_XML_NAMESPACE = "NCI_GME_XML_NAMESPACE"; //Used for projects, Packages, Classes public static final String TV_NCI_GME_XML_ELEMENT = "NCI_GME_XML_ELEMENT"; //Used for Classes public static final String TV_NCI_GME_XML_LOC_REF = "NCI_GME_XML_LOC_REF"; //Used for Attributes public static final String TV_NCI_GME_SOURCE_XML_LOC_REF = "NCI_GME_SOURCE_XML_LOC_REF"; //Used for Associations public static final String TV_NCI_GME_TARGET_XML_LOC_REF = "NCI_GME_TARGET_XML_LOC_REF"; //Used for Associations public static final String STEREO_TYPE_TABLE = "table"; public static final String STEREO_TYPE_DATASOURCE_DEPENDENCY = "DataSource"; public static final String PK_GENERATOR_SYSTEMWIDE = "NCI_GENERATOR_SYSTEMWIDE."; public static final String ISO_ROOT_PACKAGE_NAME = "gov.nih.nci.iso21090"; public static final Map<String, String> javaDatatypeMap = new HashMap<String, String>() { { put("int", "Integer"); put("integer", "Integer"); put("double", "Double"); put("float", "Float"); put("long", "Long"); put("string", "String"); put("char", "Character"); put("character", "Character"); put("boolean", "Boolean"); put("byte", "Byte"); put("byte[]", "Byte[]"); put("short", "Short"); put("date", "java.util.Date"); put("java.util.date", "java.util.Date"); put("collection<int>", "Collection<Integer>"); put("collection<integer>", "Collection<Integer>"); put("collection<double>", "Collection<Double>"); put("collection<float>", "Collection<Float>"); put("collection<long>", "Collection<Long>"); put("collection<string>", "Collection<String>"); put("collection<boolean>", "Collection<Boolean>"); put("collection<byte>", "Collection<Byte>"); put("collection<short>", "Collection<Short>"); put("collection<char>", "Collection<Character>"); put("collection<character>", "Collection<Character>"); } }; public static final Map<String, String> isoDatatypeMap = new HashMap<String, String>() { { put("BL", "Bl"); put("BL.NONNULL", "BlNonNull"); put("ST", "St"); put("ST.NT", "StNt"); put("II", "Ii"); put("TEL", "Tel"); put("TEL.PERSON", "TelPerson"); put("TEL.URL", "TelUrl"); put("TEL.PHONE", "TelPhone"); put("TEL.EMAIL", "TelEmail"); put("ED", "Ed"); put("ED.TEXT", "EdText"); put("CD", "Cd"); put("SC", "Sc"); put("INT", "Int"); put("REAL", "Real"); put("TS", "Ts"); put("PQV", "Pqv"); put("PQ", "Pq"); put("IVL<INT>", "Ivl<Int>"); put("IVL<REAL>", "Ivl<Real>"); put("IVL<TS>", "Ivl<Ts>"); put("IVL<PQV>", "Ivl<Pqv>"); put("IVL<PQ>", "Ivl<Pq>"); put("EN", "En"); put("EN.PN", "EnPn"); put("EN.ON", "EnOn"); put("DSET<II>", "DSet<Ii>"); put("DSET<TEL>", "DSet<Tel>"); put("DSET<CD>", "DSet<Cd>"); put("DSET<AD>", "DSet<Ad>"); put("AD", "Ad"); } }; public static final Map<String, String> isoDatatypeCompleteMap = new HashMap<String, String>() { { put("BL", "Bl"); put("BL.NONNULL", "BlNonNull"); put("ST", "St"); put("ST.NT", "StNt"); put("II", "Ii"); put("TEL", "Tel"); put("TEL.PERSON", "TelPerson"); put("TEL.URL", "TelUrl"); put("TEL.PHONE", "TelPhone"); put("TEL.EMAIL", "TelEmail"); put("ED", "Ed"); put("ED.TEXT", "EdText"); put("CD", "Cd"); put("SC", "Sc"); put("INT", "Int"); put("REAL", "Real"); put("TS", "Ts"); put("PQV", "Pqv"); put("PQ", "Pq"); put("IVL<INT>", "Ivl<Int>"); put("IVL<REAL>", "Ivl<Real>"); put("IVL<TS>", "Ivl<Ts>"); put("IVL<PQV>", "Ivl<Pqv>"); put("IVL<PQ>", "Ivl<Pq>"); put("EN", "En"); put("EN.PN", "EnPn"); put("EN.ON", "EnOn"); put("DSET<II>", "DSet<Ii>"); put("DSET<TEL>", "DSet<Tel>"); put("DSET<CD>", "DSet<Cd>"); put("DSET<AD>", "DSet<Ad>"); put("AD", "Ad"); put("ADXP.AL", "AdxpAl"); put("ADXP.ADL", "AdxpAdl"); put("ADXP.UNID", "AdxpUnid"); put("ADXP.UNIT", "AdxpUnit"); put("ADXP.DAL", "AdxpDal"); put("ADXP.DINST", "AdxpDinst"); put("ADXP.DINSTA", "AdxpDinsta"); put("ADXP.DINSTQ", "AdxpDinstq"); put("ADXP.DMOD", "AdxpDmod"); put("ADXP.DMODID", "AdxpDmodid"); put("ADXP.SAL", "AdxpSal"); put("ADXP.BNR", "AdxpBnr"); put("ADXP.BNN", "AdxpBnn"); put("ADXP.BNS", "AdxpBns"); put("ADXP.STR", "AdxpStr"); put("ADXP.STB", "AdxpStb"); put("ADXP.STTYP", "AdxpSttyp"); put("ADXP.DIR", "AdxpDir"); put("ADXP.INT", "AdxpInt"); put("ADXP.CAR", "AdxpCar"); put("ADXP.CEN", "AdxpCen"); put("ADXP.CNT", "AdxpCnt"); put("ADXP.CPA", "AdxpCpa"); put("ADXP.CTY", "AdxpCty"); put("ADXP.DEL", "AdxpDel"); put("ADXP.POB", "AdxpPob"); put("ADXP.PRE", "AdxpPre"); put("ADXP.STA", "AdxpSta"); put("ADXP.ZIP", "AdxpZip"); put("ADXP", "Adxp"); put("ENXP", "Enxp"); put("DSET", "DSet"); put("IVL", "Ivl"); } }; public TransformerUtils(Properties umlModelFileProperties,Properties transformerProperties,List cascadeStyles, ValidatorModel vModel, ValidatorModel vModelExtension, UMLModel model) { BASE_PKG_LOGICAL_MODEL = umlModelFileProperties.getProperty("Logical Model") == null ? "" :umlModelFileProperties.getProperty("Logical Model").trim(); BASE_PKG_DATA_MODEL = umlModelFileProperties.getProperty("Data Model")==null ? "" : umlModelFileProperties.getProperty("Data Model").trim(); EXCLUDE_PACKAGE = umlModelFileProperties.getProperty("Exclude Package")==null ? "" : umlModelFileProperties.getProperty("Exclude Package").trim(); INCLUDE_PACKAGE = umlModelFileProperties.getProperty("Include Package")==null ? "" : umlModelFileProperties.getProperty("Include Package").trim(); EXCLUDE_NAME = umlModelFileProperties.getProperty("Exclude Name")==null ? "" : umlModelFileProperties.getProperty("Exclude Name").trim(); EXCLUDE_NAMESPACE = umlModelFileProperties.getProperty("Exclude Namespace")==null ? "" : umlModelFileProperties.getProperty("Exclude Namespace").trim(); namespaceUriPrefix = transformerProperties.getProperty("namespaceUriPrefix")==null ? "" : transformerProperties.getProperty("namespaceUriPrefix").trim().replace(" ", "_"); useGMETags = transformerProperties.getProperty("useGMETags")==null ? false : Boolean.parseBoolean(transformerProperties.getProperty("useGMETags")); isJaxbEnabled = transformerProperties.getProperty("isJaxbEnabled")==null ? false : Boolean.parseBoolean(transformerProperties.getProperty("isJaxbEnabled")); isISO21090Enabled = transformerProperties.getProperty("isISO21090Enabled")==null ? false : Boolean.parseBoolean(transformerProperties.getProperty("isISO21090Enabled")); this.model = model; if (useGMETags){ setModelNamespace(model,this.getBasePkgLogicalModel()); } for(String excludeToken:EXCLUDE_PACKAGE.split(",")) EXCLUDE_PACKAGE_PATTERNS.add(excludeToken.trim()); for(String includeToken:INCLUDE_PACKAGE.split(",")) INCLUDE_PACKAGE_PATTERNS.add(includeToken.trim()); for(String excludeToken:EXCLUDE_NAME.split(",")) EXCLUDE_CLASS_PATTERNS.add(excludeToken.trim()); for(String excludeToken:EXCLUDE_NAMESPACE.split(",")) EXCLUDE_NAMESPACE_PATTERNS.add(excludeToken.trim()); IDENTITY_GENERATOR_TAG = umlModelFileProperties.getProperty("Identity Generator Tag") == null ? "": umlModelFileProperties.getProperty("Identity Generator Tag").trim(); DATABASE_TYPE = umlModelFileProperties.getProperty("Database Type") == null ? "": umlModelFileProperties.getProperty("Database Type").trim(); for (Object cascadeStyle : cascadeStyles){ CASCADE_STYLES.put((String) cascadeStyle, (String)cascadeStyle); } this.vModel = vModel; log.debug("ValidatorModel: " + vModel); this.vModelExtension = vModelExtension; log.debug("ValidatorModel Extension: " + vModelExtension); } private void setModelNamespace(UMLModel model, String basePkgLogicalModel){ //override codegen.properties NAMESPACE_PREFIX property with GME namespace tag value, if it exists try { String namespaceUriPrefix = this.getModelNamespace(model, basePkgLogicalModel); if (namespaceUriPrefix != null) { this.namespaceUriPrefix = namespaceUriPrefix; } } catch (GenerationException e) { log.error("Exception caught trying to set GME model namespace URI Prefix: ", e); } } public String getDatabaseType() { return DATABASE_TYPE; } public boolean isIncluded(UMLClass klass) throws GenerationException { String fqcn = getFQCN(klass); return isIncluded(fqcn); } public boolean isIncluded(UMLInterface interfaze) throws GenerationException { String fqcn = getFQCN(interfaze); return isIncluded(fqcn); } public boolean isIncluded(String fqcn) { log.debug("isIncluded(String fqcn) for fqcn: "+fqcn); for (String excludePkgPattern:EXCLUDE_PACKAGE_PATTERNS) if (Pattern.matches(excludePkgPattern, fqcn)) return false; for (String excludeClassPattern:EXCLUDE_CLASS_PATTERNS){ if (Pattern.matches(excludeClassPattern, fqcn)) return false; } for(String includePkgPattern: INCLUDE_PACKAGE_PATTERNS){ log.debug("includePkgPattern: "+includePkgPattern+"; fqcn: "+fqcn); if(Pattern.matches(includePkgPattern, fqcn)) return true; } return false; } public boolean isIncluded(UMLPackage pkg) throws GenerationException { String fullPkgName = getFullPackageName(pkg); log.debug("isIncluded(UMLPackage pkg) for fullPkgName: "+fullPkgName); for(String excludePkgPattern: EXCLUDE_PACKAGE_PATTERNS) if (Pattern.matches(excludePkgPattern, fullPkgName)) return false; for(String includePkgPattern: INCLUDE_PACKAGE_PATTERNS) if (Pattern.matches(includePkgPattern, fullPkgName)) return true; return true; } public boolean isNamespaceIncluded(UMLClass klass, String defaultNamespacePrefix) throws GenerationException { String pkgNamespace=null; try { pkgNamespace = getGMENamespace(klass); } catch (GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME Namespace tag value for: " + getFullPackageName(klass.getPackage()), ge); } if (pkgNamespace==null) //use default namespace pkgNamespace = defaultNamespacePrefix+getFullPackageName(klass); log.debug("* * * * * pkgNamespace:"+pkgNamespace); for(String excludePkgNamespacePattern: EXCLUDE_NAMESPACE_PATTERNS) if(Pattern.matches(excludePkgNamespacePattern,pkgNamespace)){ return false; } return true; } public String getEmptySpace(Integer count) { String spaces = ""; for(Integer i=0;i<count;i++) spaces +="\t"; return spaces; } public String getFQEN(UMLTaggableElement elt) throws GenerationException { if (elt instanceof UMLClass) return getFQCN((UMLClass)elt); if (elt instanceof UMLPackage) return getFullPackageName((UMLPackage)elt); throw new GenerationException("Error getting fully qualified element name. Supported taggable element types include UMLClass and UMLPackage; element is neither"); } public String getFQCN(UMLClass klass) { return removeBasePackage(ModelUtil.getFullName(klass)); } public String getFQCN(UMLInterface interfaze) { return removeBasePackage(ModelUtil.getFullName(interfaze)); } public String getFullPackageName(UMLTaggableElement te) { if (te instanceof UMLClass) return removeBasePackage(ModelUtil.getFullPackageName((UMLClass)te)); if (te instanceof UMLInterface) return removeBasePackage(ModelUtil.getFullPackageName((UMLInterface)te)); if (te instanceof UMLPackage) return removeBasePackage(ModelUtil.getFullPackageName((UMLPackage)te)); return ""; } private String removeBasePackage(String path) { if(path.startsWith(BASE_PKG_LOGICAL_MODEL+".")) return path.substring(BASE_PKG_LOGICAL_MODEL.length()+1); else if(path.startsWith(BASE_PKG_DATA_MODEL+".")) return path.substring(BASE_PKG_DATA_MODEL.length()+1); else return path; } public String getBasePkgLogicalModel(){ return BASE_PKG_LOGICAL_MODEL; } public String getBasePkgDataModel(){ return BASE_PKG_DATA_MODEL; } public UMLClass getSuperClass(UMLClass klass) throws GenerationException { UMLClass[] superClasses = ModelUtil.getSuperclasses(klass); if(superClasses.length == 0) { log.debug("*** Getting superclass for class " + klass.getName() + ": " + null); return null; } if(superClasses.length > 1) throw new GenerationException("Class can not have more than one super class"); log.debug("*** Getting superclass for class " + klass.getName() + ": " + superClasses[0].getName()); return superClasses[0]; } public String getSuperClassString(UMLClass klass) throws GenerationException { UMLClass superClass = getSuperClass(klass); if(superClass == null) if (isJaxbEnabled()){ return ""; } else { return ""; } else return "extends " + superClass.getName(); } public UMLInterface[] getSuperInterface(UMLInterface interfaze) throws GenerationException { UMLInterface[] superInterfaces = ModelUtil.getSuperInterfaces(interfaze); if(superInterfaces.length == 0) { log.debug("*** Getting superinterface for interface " + interfaze.getName() + ": " + null); return null; } log.debug("*** Getting superinterface for interface " + interfaze.getName() + ": " + superInterfaces[0].getName()); return superInterfaces; } public String getSuperInterfaceString(UMLInterface interfaze) throws GenerationException { String superInterfaceStr = "extends "; UMLInterface[] superInterfaces = getSuperInterface(interfaze); if(superInterfaces == null) return ""; else { superInterfaceStr += superInterfaces[0].getName(); for (int i = 1; i < superInterfaces.length; i++){ superInterfaceStr += ", " + superInterfaces[i].getName(); } } return superInterfaceStr; } public UMLInterface[] getInterfaces(UMLClass klass) throws GenerationException { UMLInterface[] interfaces = ModelUtil.getInterfaces(klass); if(interfaces.length == 0) { log.debug("*** Getting interface for class " + klass.getName() + ": " + null); return null; } log.debug("*** Getting superclass for class " + klass.getName() + ": " + interfaces[0].getName()); return interfaces; } public String getInterfaceString(UMLClass klass) throws GenerationException { UMLInterface[] interfaces = getInterfaces(klass); if(interfaces == null) return ""; else { String interfaceStr = ""; for (UMLInterface interfaze : interfaces){ interfaceStr += ", " + interfaze.getName(); } return interfaceStr; } } public String getInterfaceImports(UMLInterface interfaze) throws GenerationException { StringBuilder sb = new StringBuilder(); Set<String> importList = new HashSet<String>(); UMLInterface[] interfaces = ModelUtil.getSuperInterfaces(interfaze); String pkgName = getFullPackageName(interfaze); for (UMLInterface superInterfaze : interfaces) { String superInterfacePkg = getFullPackageName(superInterfaze); if (!pkgName.equals(superInterfacePkg)) importList.add(getFQCN(superInterfaze)); } for(String importClass:importList) sb.append("import ").append(importClass).append(";\n"); return sb.toString(); } public String getImports(UMLClass klass) throws GenerationException { StringBuilder sb = new StringBuilder(); Set<String> importList = new HashSet<String>(); UMLClass[] superClasses = ModelUtil.getSuperclasses(klass); UMLInterface[] interfaces = ModelUtil.getInterfaces(klass); if(superClasses.length>1) throw new GenerationException("Class can not have more than one super classes"); String pkgName = getFullPackageName(klass); if(superClasses.length == 1) { String superPkg = getFullPackageName(superClasses[0]); if(!pkgName.equals(superPkg)) importList.add(getFQCN(superClasses[0])); } for (UMLInterface interfaze : interfaces) { String interfacePkg = getFullPackageName(interfaze); if (!pkgName.equals(interfacePkg)) importList.add(getFQCN(interfaze)); } for(UMLAttribute attr: klass.getAttributes()) { if(getDataType(attr).startsWith("Collection") && !importList.contains("java.util.Collection")) { importList.add("java.util.Collection"); break; } } if(isISO21090Enabled) { for(UMLAttribute attr: klass.getAttributes()) { String javaName = isoDatatypeMap.get(attr.getDatatype().getName()); if(javaName!=null && javaName.indexOf("<")>0) { String collectionType = javaName.substring(0,javaName.indexOf("<")); String collectionElementType = javaName.substring(javaName.indexOf("<")+1,javaName.indexOf(">")); //String collectionName = isoDatatypeMap.get(collectionType); if (!importList.contains("gov.nih.nci.iso21090."+collectionType)) importList.add("gov.nih.nci.iso21090."+collectionType); javaName = collectionElementType; } if(javaName!=null && !importList.contains("gov.nih.nci.iso21090."+javaName)) { importList.add("gov.nih.nci.iso21090."+javaName); } } } for(UMLAssociation association: klass.getAssociations()) { List<UMLAssociationEnd> assocEnds = association.getAssociationEnds(); UMLAssociationEnd otherEnd = getOtherEnd(klass,assocEnds); String assocKlass = getFQCN ((UMLClass)otherEnd.getUMLElement()); if(!pkgName.equals(getFullPackageName ((UMLClass)otherEnd.getUMLElement())) && !importList.contains(assocKlass)) importList.add(assocKlass); if(isAssociationEndMany(otherEnd) && otherEnd.isNavigable()&& !importList.contains("java.util.Collection")) importList.add("java.util.Collection"); } importList.addAll(getHibernateValidatorConstraintImports(klass)); for(String importClass:importList) sb.append("import ").append(importClass).append(";\n"); if (isJaxbEnabled){ sb.append("\n"); sb.append("import com.sun.xml.bind.CycleRecoverable;\n"); if(isISO21090Enabled) { sb.append("import gov.nih.nci.system.client.util.xml.JAXBISOAdapter;\n"); sb.append("import gov.nih.nci.system.client.util.xml.JAXBISOIvlPqAdapter;\n"); sb.append("import gov.nih.nci.system.client.util.xml.JAXBISOIvlRealAdapter;\n"); sb.append("import gov.nih.nci.system.client.util.xml.JAXBISOIvlTsAdapter;\n"); sb.append("import gov.nih.nci.system.client.util.xml.JAXBISOIvlIntAdapter;\n"); } sb.append("import javax.xml.bind.annotation.XmlAccessType;\n"); sb.append("import javax.xml.bind.annotation.XmlAccessorType;\n"); sb.append("import javax.xml.bind.annotation.XmlAttribute;\n"); sb.append("import javax.xml.bind.annotation.XmlElementWrapper;\n"); sb.append("import javax.xml.bind.annotation.XmlElement;\n"); sb.append("import javax.xml.bind.annotation.XmlRootElement;\n"); sb.append("import javax.xml.bind.annotation.XmlSeeAlso;\n"); sb.append("import javax.xml.bind.annotation.XmlTransient;\n"); sb.append("import javax.xml.bind.annotation.XmlType;\n"); sb.append("import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;\n"); sb.append("\n"); } sb.append("import java.io.Serializable;\n"); return sb.toString(); } public String getJaxbXmlTransientAnnotation(){ return " @XmlTransient"; } public String getJaxbCollectionAnnotations(UMLClass klass, UMLClass assocKlass, String rolename){ StringBuilder sb = new StringBuilder(); sb.append(" @XmlElementWrapper(name=\"").append(rolename).append("\",\n"); sb.append(" namespace=\"").append(getNamespaceUriPrefix()).append(getFullPackageName(klass)).append("\")\n"); sb.append(" @XmlElement(name=\"").append(assocKlass.getName()).append("\",\n"); sb.append(" namespace=\"").append(getNamespaceUriPrefix()).append(getFullPackageName(assocKlass)).append("\")"); return sb.toString(); } public String getDataType(UMLAttribute attr) { UMLDatatype dataType = attr.getDatatype(); String name = dataType.getName(); if(dataType instanceof UMLClass) name = getFQCN((UMLClass)dataType); if(name.startsWith("java.lang.")) name = name.substring("java.lang.".length()); if(name.startsWith(ISO_ROOT_PACKAGE_NAME+".")) name = name.substring((ISO_ROOT_PACKAGE_NAME+".").length()); String returnValue = null; if(isISO21090Enabled) returnValue = isoDatatypeMap.get(name); if(returnValue == null) returnValue = javaDatatypeMap.get(name.toLowerCase()); return returnValue == null ? "" : returnValue; } public HashMap<String, String> getPKGeneratorTags(UMLClass table,String fqcn,UMLAttribute classIdAttr) throws GenerationException { HashMap<String, String> pkTags = new HashMap<String, String>(); String pkgenClassKey = TV_PK_GENERATOR + DATABASE_TYPE; UMLAttribute tableIdAttribute=getMappedColumn(table,fqcn+"."+classIdAttr.getName()); Collection<UMLTaggedValue> tableTaggedValues = tableIdAttribute.getTaggedValues(); String pkGeneratorClass = getTagValue(tableTaggedValues,pkgenClassKey, 1); if (pkGeneratorClass != null && !("".equals(pkGeneratorClass))) { for (int i = 1; i <= tableTaggedValues.size(); i++) { String pkgenProp = TV_PK_GENERATOR_PROPERTY + i + "."+ DATABASE_TYPE; String pkParam = getTagValue(tableTaggedValues, pkgenProp, 1); StringTokenizer tokenizer = new StringTokenizer(pkParam, ":"); if(tokenizer.hasMoreTokens()){ pkTags.put(tokenizer.nextToken(), tokenizer.nextToken()); } } pkTags.put(pkgenClassKey, pkGeneratorClass); } else { pkTags.put(PK_GENERATOR_SYSTEMWIDE+DATABASE_TYPE, IDENTITY_GENERATOR_TAG); } return pkTags; } public String getHibernateDataType(UMLClass klass, UMLAttribute attr) throws GenerationException { log.debug("getHibernateDataType for klass: " + klass.getName() + ", attr: " + attr.getName()); String fqcn = getFQCN(klass); UMLClass table = getTable(klass); UMLAttribute col = getMappedColumn(table,fqcn+"."+attr.getName()); Boolean isClob = "CLOB".equalsIgnoreCase(getTagValue(col.getTaggedValues(),TV_TYPE, 1)); UMLDatatype dataType = attr.getDatatype(); String name = dataType.getName(); if(dataType instanceof UMLClass) name = getFQCN((UMLClass)dataType); if(name.startsWith("java.lang.")) name = name.substring("java.lang.".length()); if(isClob && "string".equalsIgnoreCase(name)) return "text"; if(isClob && !"string".equalsIgnoreCase(name)) throw new GenerationException("Can not map CLOB to anything other than String"); if("byte[]".equalsIgnoreCase(name)) return "org.springframework.orm.hibernate3.support.BlobByteArrayType"; if("int".equalsIgnoreCase(name) || "integer".equalsIgnoreCase(name)) return "integer"; if("double".equalsIgnoreCase(name)) return "double"; if("float".equalsIgnoreCase(name)) return "float"; if("long".equalsIgnoreCase(name)) return "long"; if("string".equalsIgnoreCase(name)) return "string"; if("char".equalsIgnoreCase(name) || "character".equalsIgnoreCase(name)) return "character"; if("boolean".equalsIgnoreCase(name) ) return "boolean"; if("byte".equalsIgnoreCase(name) ) return "byte"; if("short".equalsIgnoreCase(name) ) return "short"; if("date".equalsIgnoreCase(name) || "java.util.date".equalsIgnoreCase(name)) return "java.util.Date"; if(isISO21090Enabled) { if(name.startsWith(ISO_ROOT_PACKAGE_NAME+".")) name = name.substring((ISO_ROOT_PACKAGE_NAME+".").length()); if("II".equals(name)) return "gov.nih.nci.iso21090.hibernate.usertype.IiUserType"; } //log.info("Type = "+name); return name; } public String getGetterMethodName(UMLAttribute attr) { String name = attr.getName(); return "get"+name.substring(0,1).toUpperCase()+name.substring(1,name.length()); } public String getSetterMethodName(UMLAttribute attr) { String name = attr.getName(); return "set"+name.substring(0,1).toUpperCase()+name.substring(1,name.length()); } public UMLAssociationEnd getThisEnd(UMLClass klass, List<UMLAssociationEnd>assocEnds) throws GenerationException { UMLAssociationEnd end1 = assocEnds.get(0); UMLAssociationEnd end2 = assocEnds.get(1); if(end1.getUMLElement().equals(klass)) return end1; else if(end2.getUMLElement().equals(klass)) return end2; else throw new GenerationException("Could not figureout this end"); } public UMLAssociationEnd getOtherEnd(UMLClass klass, List<UMLAssociationEnd>assocEnds) throws GenerationException { UMLAssociationEnd end1 = assocEnds.get(0); UMLAssociationEnd end2 = assocEnds.get(1); if(end1.getUMLElement().equals(klass)) return end2; else if(end2.getUMLElement().equals(klass)) return end1; else throw new GenerationException("Could not figureout other end" ); } public Boolean isAssociationEndMany(UMLAssociationEnd assocEnd) { if((assocEnd.getHighMultiplicity()<0)||(assocEnd.getLowMultiplicity()<0)) return true; else return false; } public Boolean isImplicitParent(UMLAssociationEnd assocEnd) { return isImplicitParent((UMLClass)assocEnd.getUMLElement()); } public String getGetterMethodName(UMLAssociationEnd assocEnd) { String name = assocEnd.getRoleName(); return "get"+name.substring(0,1).toUpperCase()+name.substring(1,name.length()); } public String getSetterMethodName(UMLAssociationEnd assocEnd) { String name = assocEnd.getRoleName(); return "set"+name.substring(0,1).toUpperCase()+name.substring(1,name.length()); } public Boolean isSelfAssociation(UMLAssociationEnd assocEnd1,UMLAssociationEnd assocEnd2) { return assocEnd1.getUMLElement().equals(assocEnd2.getUMLElement()); } public String getClassIdGetterMthod(UMLClass klass) throws GenerationException { String idAttrName = getClassIdAttrName(klass); if (idAttrName == null) return null; return "get"+firstCharUpper(getClassIdAttrName(klass)); } private String firstCharUpper(String data) { if(data == null || data.length() == 0) return data; return Character.toUpperCase(data.charAt(0)) + data.substring(1); } public String getClassIdAttrName(UMLClass klass) throws GenerationException { UMLAttribute idAttr = getClassIdAttr(klass); if (idAttr == null) return null; return getClassIdAttr(klass).getName(); } public UMLAttribute getClassIdAttr(UMLClass klass) throws GenerationException { String fqcn = getFQCN(klass); UMLAttribute idAttr = getColumn(klass,TV_ID_ATTR_COLUMN, fqcn,true,0,1); if(idAttr !=null) return idAttr; String idAttrName = "id"; for(UMLAttribute attribute:klass.getAttributes()) if(idAttrName.equals(attribute.getName())) return attribute; for(UMLGeneralization gen: klass.getGeneralizations()) { if(gen.getSubtype() == klass && gen.getSupertype() != klass) { UMLAttribute superId = getClassIdAttr((UMLClass)gen.getSupertype()); if(superId != null) return superId; } } return null; //throw new GenerationException("No attribute found that maps to the primary key identifier for class : "+fqcn); } public Boolean isCollection(UMLClass klass, UMLAttribute attr ) throws GenerationException { if(getDataType(attr).startsWith("Collection")) return true; return false; } public boolean isStatic(UMLAttribute att){ UMLTaggedValue tValue = att.getTaggedValue("static"); if (tValue == null) { return false; } log.debug("UMLAttribute 'static' Tagged Value: " + tValue.getValue()); return ("1".equalsIgnoreCase(tValue.getValue())); } public boolean isAbstract(UMLClass klass){ return klass.getAbstractModifier().isAbstract(); } public String getType(UMLAssociationEnd assocEnd){ UMLTaggedValue tValue = assocEnd.getTaggedValue("type"); if (tValue == null) { return ""; } log.debug("UMLAttribute Type Tagged Value: " + tValue.getValue()); return tValue.getValue(); } public UMLAssociationEnd getOtherAssociationEnd(UMLAssociationEnd assocEnd) { UMLAssociationEnd otherAssocEnd = null; for (Iterator i = assocEnd.getOwningAssociation().getAssociationEnds().iterator(); i .hasNext();) { UMLAssociationEnd ae = (UMLAssociationEnd) i.next(); if (ae != assocEnd) { otherAssocEnd = ae; break; } } return otherAssocEnd; } public String getUpperBound(UMLAssociationEnd otherEnd) { int multiplicity = otherEnd.getHighMultiplicity(); String finalMultiplicity = new String(); if (multiplicity == -1) { finalMultiplicity = "unbounded"; } else { Integer x = new Integer(multiplicity); finalMultiplicity = x.toString(); } return finalMultiplicity; } public String getLowerBound(UMLAssociationEnd otherEnd) { int multiplicity = otherEnd.getLowMultiplicity(); String finalMultiplicity = new String(); if (multiplicity == -1) { finalMultiplicity = "unbounded"; } else { Integer x = new Integer(multiplicity); finalMultiplicity = x.toString(); } return finalMultiplicity; } public String getMultiplicityValue(UMLAssociationEnd assocEnd){ Element element = ((UMLAssociationEndBean)assocEnd).getJDomElement(); org.jdom.Attribute multAtt = element.getAttribute("multiplicity"); //log.debug("associationEnd: " + assocEnd.getRoleName() + "; multiplicity: " + multAtt.getValue()); if (multAtt!=null) return multAtt.getValue(); int low = assocEnd.getLowMultiplicity(); int high = assocEnd.getHighMultiplicity(); if(low <0 && high<0) return ""; if(low >=0 && high>=0) return low+".."+high; if(low<0) return high+""; return low+""; } public boolean isMultiplicityValid(UMLAssociationEnd assocEnd){ String multValue = getMultiplicityValue(assocEnd); if(multValue == null || "".equalsIgnoreCase(multValue) || multValue.startsWith(".") || multValue.endsWith(".")) return false; return true; } /** * @param thisEnd * @param otherEnd * @return */ public boolean isMany2One(UMLAssociationEnd thisEnd, UMLAssociationEnd otherEnd) { return isAssociationEndMany(thisEnd) && !isAssociationEndMany(otherEnd); } /** * @param thisEnd * @param otherEnd * @return */ public boolean isAny(UMLAssociationEnd thisEnd,UMLAssociationEnd otherEnd) { return isAssociationEndMany(thisEnd) && !isAssociationEndMany(otherEnd) && isImplicitParent(otherEnd); } /** * @param thisEnd * @param otherEnd * @return */ public boolean isOne2Many(UMLAssociationEnd thisEnd,UMLAssociationEnd otherEnd) { return !isAssociationEndMany(thisEnd) && isAssociationEndMany(otherEnd); } /** * @param thisEnd * @param otherEnd * @return */ public boolean isMany2Many(UMLAssociationEnd thisEnd,UMLAssociationEnd otherEnd) { return isAssociationEndMany(thisEnd) && isAssociationEndMany(otherEnd); } /** * @param thisEnd * @param otherEnd * @return */ public boolean isMany2Any(UMLAssociationEnd thisEnd,UMLAssociationEnd otherEnd) { return isAssociationEndMany(thisEnd) && isAssociationEndMany(otherEnd) && isImplicitParent(otherEnd); } /** * @param thisEnd * @param otherEnd * @return */ public boolean isOne2One(UMLAssociationEnd thisEnd,UMLAssociationEnd otherEnd) { return !isAssociationEndMany(thisEnd) && !isAssociationEndMany(otherEnd); } public Collection getAssociationEnds(UMLClass klass) { return getAssociationEnds(klass, false); } public Collection getAssociationEnds(UMLClass klass, boolean includeInherited) { log.debug("class = " + klass.getName() + ", includeInherited = " + includeInherited); List<UMLAssociationEnd> assocEndsList = new ArrayList<UMLAssociationEnd>(); UMLClass superClass = klass; while (superClass != null) { Collection assocs = superClass.getAssociations(); log.debug( superClass.getName() + " association collection size(): " + assocs.size()); for (Iterator i = assocs.iterator(); i.hasNext();) { UMLAssociation assoc = (UMLAssociation) i.next(); for (UMLAssociationEnd ae:assoc.getAssociationEnds()){ UMLAssociationEnd otherEnd = getOtherAssociationEnd(ae); String id = ((UMLClass)(otherEnd.getUMLElement())).getName() + Constant.LEFT_BRACKET + getFQCN((UMLClass)(otherEnd.getUMLElement())) + Constant.RIGHT_BRACKET; log.debug("id (otherEnd): " + id); log.debug("superClass: " + superClass.getName()); if ((UMLClass)ae.getUMLElement() == superClass) { log.debug("adding association: " + id + " for class " + superClass.getName()); assocEndsList.add(ae); } } } if (includeInherited) { // TODO :: Implement includeInherited // Collection gens = superClass.getGeneralization(); // if (gens.size() > 0) { // superClass = (Classifier) ((Generalization) gens.iterator() // .next()).getParent(); // } else { // superClass = null; log.debug("Need to implement includeInherited"); } else { superClass = null; } } return assocEndsList; } public void collectPackages(Collection<UMLPackage> nextLevelPackages, Hashtable<String, Collection<UMLClass>> pkgColl) throws GenerationException { for(UMLPackage pkg:nextLevelPackages){ if (isIncluded(pkg)){ String pkgName=getFullPackageName(pkg); log.debug("including package: " + pkgName); Collection<UMLClass> pkgClasses = pkg.getClasses(); if (pkgClasses != null && pkgClasses.size() > 0){ for (UMLClass klass:pkgClasses){ if(!STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype()) && isIncluded(klass)) { if(!pkgColl.containsKey(pkgName)) { List<UMLClass> classes = new ArrayList<UMLClass>(); classes.add(klass); pkgColl.put(pkgName, classes); } else { Collection<UMLClass> existingCollection = pkgColl.get(pkgName); existingCollection.add(klass); } } } } } else{ log.debug("excluding package: " + pkg.getName()); } collectPackages(pkg.getPackages(), pkgColl); } } public void collectPackages(Collection<UMLClass> allClasses, Hashtable<String, Collection<UMLClass>> pkgColl,String defaultNamespacePrefix) throws GenerationException { String pkgName=null; String pkgNamespace=null; for(UMLClass klass:allClasses){ pkgName = getGMEPackageName(klass); if (pkgName == null) pkgName=getFullPackageName(klass); log.debug("processing klass: " + klass.getName() + " of package " + pkgName); if (isNamespaceIncluded(klass,defaultNamespacePrefix)){ log.debug("including package: " + pkgName); if(!STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype()) && isIncluded(klass)) { //No longer using GME ClassName; e.g., no longer using isIncluded(pkgName+"."+getClassName(klass))) { pkgNamespace=getGMENamespace(klass); if (pkgNamespace !=null && (pkgNamespace.endsWith("/") || !pkgNamespace.endsWith(pkgName))) pkgNamespace=pkgNamespace+pkgName; log.debug("pkgNamespace: " + pkgNamespace); if(!pkgColl.containsKey(pkgNamespace)) { List<UMLClass> classes = new ArrayList<UMLClass>(); classes.add(klass); pkgColl.put(pkgNamespace, classes); } else { Collection<UMLClass> existingCollection = pkgColl.get(pkgNamespace); existingCollection.add(klass); } } } else{ log.debug("excluding class: " +klass.getName()+" with package: " + pkgName); } } } public String getGMEPackageName(UMLClass klass) throws GenerationException{ String namespacePkgName = null; try { namespacePkgName = getNamespacePackageName(klass); if (namespacePkgName!=null && namespacePkgName.length()>0) return namespacePkgName; } catch(GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME package name for: " + getFQEN(klass), ge); } namespacePkgName=getGMEPackageName(klass.getPackage()); if (namespacePkgName!=null && namespacePkgName.length()>0) return namespacePkgName; log.debug("GME Package name not found for: "+getFullPackageName(klass)+". Returning null"); return null; } public String getGMEPackageName(UMLPackage pkg) throws GenerationException{ if (pkg==null) return null; log.debug("Getting Package Name for: " +pkg.getName()); String namespacePkgName = getNamespacePackageName(pkg); if (namespacePkgName!=null && namespacePkgName.length()>0) return namespacePkgName; return getGMEPackageName(pkg.getParent()); } private String getClassName(UMLClass klass)throws GenerationException{ try { String klassName = getXMLClassName(klass); if (klassName!=null) return klassName; } catch(GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME Class (XML Element) name for klass: " + getFQCN(klass)); } return klass.getName(); } /** * Returns all the classes (not the tables) in the XMI file which do not belong to java.lang or java.util package * @param model * @return */ public Collection<UMLClass> getAllClasses(UMLModel model) throws GenerationException { Collection<UMLClass> classes = null; try { classes = new HashSet<UMLClass>(); getAllClasses(model.getPackages(),classes); } catch(Exception e){ log.error("Unable to retrieve classes from model: ", e); throw new GenerationException("Unable to retrieve classes from model: ", e); } return classes; } private void getAllClasses(Collection<UMLPackage> pkgCollection,Collection<UMLClass> classes)throws GenerationException { for(UMLPackage pkg:pkgCollection) getAllClasses(pkg,classes); } private void getAllClasses(UMLPackage rootPkg,Collection<UMLClass> classes) throws GenerationException { if(isIncluded(rootPkg)) { for(UMLClass klass:rootPkg.getClasses()) { if(!STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype()) && isIncluded(klass)) classes.add(klass); } } getAllClasses(rootPkg.getPackages(),classes); } /** * Returns all the interfaces in the XMI file which do not belong to java.lang or java.util package * @param model * @return */ public Collection<UMLInterface> getAllInterfaces(UMLModel model) throws GenerationException { Collection<UMLInterface> interfaces = null; try { interfaces = new HashSet<UMLInterface>(); getAllInterfaces(model.getPackages(),interfaces); } catch(Exception e){ log.error("Unable to retrieve interfaces from model: ", e); throw new GenerationException("Unable to retrieve interfaces from model: ", e); } return interfaces; } private void getAllInterfaces(Collection<UMLPackage> pkgCollection,Collection<UMLInterface> interfaces)throws GenerationException { for(UMLPackage pkg:pkgCollection) getAllInterfaces(pkg,interfaces); } private void getAllInterfaces(UMLPackage rootPkg,Collection<UMLInterface> interfaces) throws GenerationException { if(isIncluded(rootPkg)) { for(UMLInterface interfaze:rootPkg.getInterfaces()) { if(!STEREO_TYPE_TABLE.equalsIgnoreCase(interfaze.getStereotype()) && isIncluded(interfaze)) interfaces.add(interfaze); } } getAllInterfaces(rootPkg.getPackages(),interfaces); } public Collection<UMLClass> getAllHibernateClasses(UMLModel model) throws GenerationException { Collection<UMLClass> allHibernateClasses = getAllParentClasses(model); allHibernateClasses.addAll(getAllImplicitParentLeafClasses(model)); return allHibernateClasses; } /** * Returns all the classes (not the tables) in the XMI file which do not belong to java.lang or java.util package. * The class also have to be the root class in the inheritnace hierarchy to be included in the final list * @param model * @return */ public Collection<UMLClass> getAllParentClasses(UMLModel model) throws GenerationException { Collection<UMLClass> classes = new ArrayList<UMLClass>(); getAllParentClasses(model.getPackages(),classes); return classes; } private void getAllParentClasses(Collection<UMLPackage> pkgCollection,Collection<UMLClass> classes) throws GenerationException { for(UMLPackage pkg:pkgCollection) getAllParentClasses(pkg,classes); } private void getAllParentClasses(UMLPackage rootPkg,Collection<UMLClass> classes)throws GenerationException { if(isIncluded(rootPkg)) { for(UMLClass klass:rootPkg.getClasses()) { if(!STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype()) && isIncluded(klass) && ModelUtil.getSuperclasses(klass).length == 0 && !isImplicitParent(klass)) classes.add(klass); } } getAllParentClasses(rootPkg.getPackages(),classes); } /** * Returns all the classes (not the tables) in the XMI file which do not belong to java.lang or java.util package. * The class also has to be an implicit parent (parent class with no table mapping) in the inheritance hierarchy to be included in the final list * @param model * @return */ public Collection<UMLClass> getAllImplicitParentLeafClasses(UMLModel model) throws GenerationException { Collection<UMLClass> classes = new ArrayList<UMLClass>(); getAllImplicitParentLeafClasses(model.getPackages(),classes); return classes; } private void getAllImplicitParentLeafClasses(Collection<UMLPackage> pkgCollection,Collection<UMLClass> classes) throws GenerationException { for(UMLPackage pkg:pkgCollection) getAllImplicitParentLeafClasses(pkg,classes); } private void getAllImplicitParentLeafClasses(UMLPackage rootPkg,Collection<UMLClass> classes) throws GenerationException { if(isIncluded(rootPkg)) { for(UMLClass klass:rootPkg.getClasses()) { try { if(!STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype()) && isIncluded(klass) && isImplicitParent(getSuperClass(klass)) && !isImplicitParent(klass)) classes.add(klass); } catch(GenerationException e){ continue; } } } getAllImplicitParentLeafClasses(rootPkg.getPackages(),classes); } /** * Retrieves the table corresponding to the Dependency link between class and a table. * If there are no Dependencies that links the class to table or there is more than * one Dependency then the method throws an exception * * @param klass * @return * @throws GenerationException */ public UMLClass getTable(UMLClass klass) throws GenerationException { Set<UMLDependency> dependencies = klass.getDependencies(); Map<String,UMLClass> clientMap = new HashMap<String,UMLClass>(); int count = 0; UMLClass result = null; for(UMLDependency dependency:dependencies) { UMLClass client = (UMLClass) dependency.getClient(); log.debug("getTable: klass: " + klass.getName() + "Client stereotype: " +client.getStereotype() + "; dependency stereotype: " + dependency.getStereotype()); if(STEREO_TYPE_TABLE.equalsIgnoreCase(client.getStereotype()) && STEREO_TYPE_DATASOURCE_DEPENDENCY.equalsIgnoreCase(dependency.getStereotype())) { log.debug("* * * client.getName(): " + client.getName()); clientMap.put(client.getName(), client); result = client; } } count = clientMap.size(); if(count!=1){ log.debug("getTable: klass: " +klass.getName()+"; count: " + count); throw new GenerationException("No table found for : "+getFQCN(klass)+". Make sure the corresponding Data Model table (class) has a 'table' Stereotype assigned, and the Dependency between the Data Model table and Logical Model class has a 'DataSource' Stereotype assigned."); } return result; } /** * Determines whether the input class is an implicit superclass. Used * by the code generator to determine whether an implicit inheritance * hibernate mapping should be created for the input class * @param klass * @return * @throws GenerationException */ public boolean isImplicitParent(UMLClass klass) { if (klass != null) log.debug("isImplicitClass " + klass.getName()+": " + (isSuperclass(klass) && hasNoTableMapping(klass))); return (isSuperclass(klass) && hasNoTableMapping(klass)); } public boolean hasImplicitParent(UMLClass klass){ UMLClass superclass = klass; do { try { superclass = getSuperClass(superclass); if(isImplicitParent(superclass)){ return true; } } catch (GenerationException e) { log.error("ERROR encountered checking if class " +klass.getName() + " has an implicit parent: ", e); return false; } } while (!(superclass==null) && !(superclass.getName().equalsIgnoreCase("java.lang.Object"))); return false; } /** * Determines whether the input class is a superclass * @param klass * @return */ private boolean isSuperclass(UMLClass klass) { boolean isSuperClass = false; if (klass != null) for(UMLGeneralization gen:klass.getGeneralizations()) { if(gen.getSupertype() instanceof UMLClass && ((UMLClass)gen.getSupertype()) == klass) return true; } return isSuperClass; } /** * Determines whether the input class is missing a table mapping * @param klass * @return */ private boolean hasNoTableMapping(UMLClass klass) { try { getTable(klass); } catch (GenerationException e){ return true; } return false; } /** * Scans the tag values of the association to determine which JOIN table the association is using. * * @param association * @param model * @param klass * @return * @throws GenerationException */ public UMLClass findCorrelationTable(UMLAssociation association, UMLModel model, UMLClass klass) throws GenerationException { return findCorrelationTable(association, model, klass, true); } public UMLClass findCorrelationTable(UMLAssociation association, UMLModel model, UMLClass klass, boolean throwException) throws GenerationException { int minReq = throwException ? 1:0; String tableName = getTagValue(klass, association,TV_CORRELATION_TABLE, null,minReq,1); if(!throwException && (tableName == null || tableName.length() ==0)) return null; UMLClass correlationTable = ModelUtil.findClass(model,BASE_PKG_DATA_MODEL+"."+tableName); if(correlationTable == null) throw new GenerationException("No correlation table found named : \""+tableName+"\""); return correlationTable; } public String getMappedColumnName(UMLClass table, String fullyQualifiedAttrName) throws GenerationException { return getColumnName(table,TV_MAPPED_ATTR_COLUMN,fullyQualifiedAttrName,false,1,1); } public UMLAttribute getMappedColumn(UMLClass table, String fullyQualifiedAttrName) throws GenerationException { return getColumn(table,TV_MAPPED_ATTR_COLUMN,fullyQualifiedAttrName,false,1,1); } /** * @param tgElt The TaggableElement (UMLClass, UMLAttribute) * @return String containing a concatenation of any, all caDSR * tag values */ public String getCaDSRAnnotationContent(UMLTaggableElement tgElt) { String publicID = getTagValue(tgElt, TV_CADSR_PUBLICID); String version = getTagValue(tgElt, TV_CADSR_VERSION); if (publicID == null && version == null) { return null; } StringBuilder sb = new StringBuilder(); if (publicID != null) sb.append(TV_CADSR_PUBLICID).append("=\"").append(publicID).append("\"; "); if (version != null) sb.append(TV_CADSR_VERSION).append("=\"").append(version).append("\""); return sb.toString(); } public String findAssociatedColumn(UMLClass table,UMLClass klass, UMLAssociationEnd otherEnd, UMLClass assocKlass, UMLAssociationEnd thisEnd, Boolean throwException, Boolean isJoin) throws GenerationException { String col1 = getColumnName(table,TV_ASSOC_COLUMN,getFQCN(klass) +"."+ otherEnd.getRoleName(),false,0,1); String col2 = getColumnName(table,TV_ASSOC_COLUMN,getFQCN(assocKlass) +"."+ thisEnd.getRoleName(),false,0,1); String col3 = getColumnName(table,TV_INVERSE_ASSOC_COLUMN,getFQCN(assocKlass) +"."+ thisEnd.getRoleName(),false,0,1); log.debug("***** col1: " + col1 + "; col2: " + col2 + "; col3: " + col3); if("".equals(col1)) col1=null; if("".equals(col2)) col2=null; if("".equals(col3)) col3=null; if((col1==null && col3==null && isJoin && throwException) || (col1==null && col2==null && !isJoin && throwException)){ log.debug("***** col1: " + col1 + "; col2: " + col2 + "; col3: " + col3); log.debug("klass: " + klass.getName()); log.debug("assocKlass: " + assocKlass.getName()); log.debug("table: " + table.getName()); log.debug("isJoin: " + isJoin); log.debug("otherEnd.getRoleName(): " +otherEnd.getRoleName()); log.debug("thisEnd.getRoleName(): " +thisEnd.getRoleName()); throw new GenerationException("Could not determine the column for the association between "+getFQCN(klass)+" and "+getFQCN(assocKlass) +". Check for missing implements-association/inverse-of/correlation-table tag(s), where appropriate"); } /*if(col1!=null && col2!=null && !col1.equals(col2)) throw new GenerationException("More than one column found for the association between "+getFQCN(klass)+" and "+getFQCN(assocKlass)); if(col1!=null && col3!=null && !col1.equals(col3)) throw new GenerationException("More than one column found for the association between "+getFQCN(klass)+" and "+getFQCN(assocKlass)); if(col2!=null && col3!=null && !col2.equals(col3)) throw new GenerationException("More than one column found for the association between "+getFQCN(klass)+" and "+getFQCN(assocKlass)); */ if(isJoin) { return col1==null ? col3 : col1; } else { return col1==null ? col2 : col1; } /* if(col1!=null) return col1; else if (col3!=null) return col3; else return col2; */ } public String findAssociatedColumn(UMLClass table,UMLClass klass, UMLAssociationEnd otherEnd, UMLClass assocKlass, UMLAssociationEnd thisEnd, Boolean isJoin) throws GenerationException { return findAssociatedColumn(table,klass, otherEnd, assocKlass, thisEnd, true, isJoin); } public String findInverseColumnValue(UMLClass table,UMLClass klass, UMLAssociationEnd thisEnd) throws GenerationException { return getColumnName(table,TV_INVERSE_ASSOC_COLUMN,getFQCN(klass) +"."+ thisEnd.getRoleName(),false,0,1); } public String findDiscriminatingColumnName(UMLClass klass) throws GenerationException { UMLClass superKlass = klass; UMLClass temp = klass; while ((temp = getSuperClass(temp))!=null && !isImplicitParent(temp)) superKlass = temp; UMLClass table = getTable(superKlass); String fqcn = getFQCN(superKlass); return getColumnName(table,TV_DISCR_COLUMN,fqcn,false,0,1); } public String getDiscriminatorValue(UMLClass klass) throws GenerationException { return getTagValue(klass,TV_DISCR_COLUMN,null, 1,1); } public String getRootDiscriminatorValue(UMLClass klass) throws GenerationException { return getTagValue(klass,TV_DISCR_COLUMN,null,0,1); } public String getImplicitDiscriminatorColumn(UMLClass table, UMLClass klass, String roleName) throws GenerationException { log.debug("**** getImplicitDiscriminator: table: " + table.getName() +"; klass: " + klass.getName() +"; roleName: " + roleName); return getColumnName(table,TV_DISCR_COLUMN,getFQCN(klass)+"."+roleName,false,1,1); } public String getImplicitIdColumn(UMLClass table, UMLClass klass, String roleName) throws GenerationException { return getColumnName(table,TV_ASSOC_COLUMN,getFQCN(klass)+"."+roleName,false,1,1); } public boolean isLazyLoad(UMLClass klass, UMLAssociation association) throws GenerationException { String temp = getTagValue(klass,association, TV_LAZY_LOAD,null, 0,1); if (temp != null) throw new GenerationException("Invalid Tag Value found: The '" + TV_LAZY_LOAD + "' Tag Value which is attached to the association link has been replaced with the '" + TV_NCI_EAGER_LOAD + "' Tag Value. Also, it's value must now conform to the following pattern: "+TV_NCI_EAGER_LOAD+"#<fully qualified class name>.<role name>. The value of the tag continues to be 'yes' or 'no'. Please update your model accordingly" ); return true; } private String getTagValue(UMLTaggableElement elt, String key, String value, int minOccurrence, int maxOccurrence) throws GenerationException { String result = null; int count = 0; for(UMLTaggedValue tv: elt.getTaggedValues()) { if (key.equals(tv.getName())) { String tvValue = tv.getValue(); String[] tvValues = tvValue.split(","); for(String val:tvValues) { if(value==null) { count++; result = val; } else if(value.equals(val)) { count++; result = val; } } } } if(count < minOccurrence || (minOccurrence>0 && (result == null || result.trim().length() == 0))) throw new GenerationException("No value found for "+key+" tag in : "+getFQEN(elt)); if(count > maxOccurrence) throw new GenerationException("More than one value found for "+key+" tag in : "+getFQEN(elt)); return result; } public String getTagValue(UMLTaggableElement tgElt, String key) { for(UMLTaggedValue tv: tgElt.getTaggedValues()) { if (key.equals(tv.getName())) { return tv.getValue(); } } return null; } private List<String> getTagValues(UMLTaggableElement tgElt, String key) { List<String> tagValues = new ArrayList<String>(); for(UMLTaggedValue tv: tgElt.getTaggedValues()) { if (key.equals(tv.getName())) { log.debug(tv.getName() + ": " + tv.getValue()); tagValues.add(tv.getValue()); } } return tagValues; } public String getColumnName(UMLClass klass, String key, String value, boolean isValuePrefix, int minOccurrence, int maxOccurrence) throws GenerationException { UMLAttribute attr = getColumn(klass,key,value,isValuePrefix,minOccurrence,maxOccurrence); return (attr==null) ? "" : attr.getName(); } private UMLAttribute getColumn(UMLClass klass, String key, String value, boolean isValuePrefix, int minOccurrence, int maxOccurrence) throws GenerationException { UMLAttribute result = null; int count = 0; for(UMLAttribute attr: klass.getAttributes()) { for(UMLTaggedValue tv: attr.getTaggedValues()) { if (key.equals(tv.getName())) { String tvValue = tv.getValue(); String[] tvValues = tvValue.split(","); for(String val:tvValues) { if(value==null) { count++; result = attr; } else if(isValuePrefix && val.startsWith(value)) { count++; result = attr; } else if(!isValuePrefix && val.equals(value)) { count++; result = attr; } } } } } if(count < minOccurrence) throw new GenerationException("No value of "+value+" found for "+key+" tag in class : "+getFQCN(klass)); if(count > maxOccurrence) throw new GenerationException("More than one values found for "+key+" tag in class : "+getFQCN(klass)); return result; } public String getTagValue(UMLClass klass, UMLAttribute attribute, String key, String value, Boolean isValuePrefix, int minOccurrence, int maxOccurrence) throws GenerationException { String result = null; int count = 0; for(UMLTaggedValue tv: attribute.getTaggedValues()) { log.debug("Processing tv: " + tv.getName()); if (key.equals(tv.getName())) { String tvValue = tv.getValue(); log.debug("Key equals tv. TV value is: " + tv.getValue()); String[] tvValues = tvValue.split(","); for(String val:tvValues) { if(value==null) { count++; result = val; } else if(isValuePrefix && val.startsWith(value)) { count++; result = val; } else if(!isValuePrefix && val.equals(value)) { count++; result = val; } } } } if(count < minOccurrence) throw new GenerationException("No value of "+value+" found for "+key+" tag in class : "+getFQCN(klass)); if(count > maxOccurrence) throw new GenerationException("More than one values found for "+key+" tag in class : "+getFQCN(klass)); return result; } private String getTagValue(UMLClass klass, UMLAssociation association, String key, String value, Boolean isValuePrefix, int minOccurrence, int maxOccurrence) throws GenerationException { List <UMLAssociationEnd>ends = association.getAssociationEnds(); UMLAssociationEnd thisEnd = getThisEnd(klass, ends); UMLAssociationEnd otherEnd = getOtherEnd(klass, ends); String thisClassName = getFQCN(((UMLClass)thisEnd.getUMLElement())); String otherClassName = getFQCN(((UMLClass)otherEnd.getUMLElement())); String result = null; int count = 0; for(UMLTaggedValue tv: association.getTaggedValues()) { if (key.equals(tv.getName())) { String tvValue = tv.getValue(); String[] tvValues = tvValue.split(","); for(String val:tvValues) { if(value==null) { count++; result = val; } else if(isValuePrefix && val.startsWith(value)) { count++; result = val; } else if(!isValuePrefix && val.equals(value)) { count++; result = val; } } } } if(count < minOccurrence || (minOccurrence >0 && (result == null || result.trim().length() == 0))) throw new GenerationException("No tag value of "+key+" found for the association between "+thisClassName +" and "+ otherClassName +":"+count+":"+result); if(count > maxOccurrence) throw new GenerationException("More than the expected maximum number (" + maxOccurrence + ") of tag value occurrences for "+key+" found for the association between "+thisClassName +" and "+ otherClassName); return result; } private String getTagValue(UMLClass klass, UMLAssociation association, String key, String value, int minOccurrence, int maxOccurrence) throws GenerationException { return getTagValue(klass, association, key, value,false, minOccurrence, maxOccurrence); } public String getTagValue(Collection<UMLTaggedValue> tagValues, String key, int maxOccurrence) throws GenerationException { StringBuilder temp = new StringBuilder(); for(int i=0;i<maxOccurrence;i++) { String searchKey = i==0 ? key : key + (i+1); for(UMLTaggedValue tv:tagValues) { if(searchKey.equals(tv.getName())) { temp.append(tv.getValue()); } } } return temp.toString(); } private String getJavaDocs(Collection<UMLTaggedValue> tagValues) throws GenerationException { String documentation = getTagValue(tagValues, TV_DOCUMENTATION, 8); String description = getTagValue(tagValues, TV_DESCRIPTION, 8); String temp = documentation == null || documentation.trim().length()==0 ? description : documentation; StringBuilder doc = new StringBuilder(); doc.append("/**"); doc.append("\n\t* ").append(temp); doc.append("\n\t**/"); return doc.toString(); } public String getJavaDocs(UMLInterface interfaze) throws GenerationException { return getJavaDocs(interfaze.getTaggedValues()); } public String getJavaDocs(UMLClass klass) throws GenerationException { return getJavaDocs(klass.getTaggedValues()); } public String getJavaDocs(UMLAttribute attr) throws GenerationException { return getJavaDocs(attr.getTaggedValues()); } public String getJavaDocs(UMLClass klass, UMLAssociation assoc) throws GenerationException { UMLAssociationEnd otherEnd = getOtherEnd(klass, assoc.getAssociationEnds()); StringBuilder doc = new StringBuilder(); doc.append("/**"); doc.append("\n * An associated "+getFQCN(((UMLClass)otherEnd.getUMLElement()))+" object"); if(isAssociationEndMany(otherEnd)) doc.append("'s collection "); doc.append("\n **/\n"); return doc.toString(); } public String getGetterMethodJavaDocs(UMLAttribute attr) { StringBuilder doc = new StringBuilder(); doc.append("/**"); doc.append("\n * Retrieves the value of the "+attr.getName()+" attribute"); doc.append("\n * @return ").append(attr.getName()); doc.append("\n **/\n"); return doc.toString(); } public String getSetterMethodJavaDocs(UMLAttribute attr) { StringBuilder doc = new StringBuilder(); doc.append("/**"); doc.append("\n * Sets the value of "+attr.getName()+" attribute"); doc.append("\n **/\n"); return doc.toString(); } public String getGetterMethodJavaDocs(UMLClass klass, UMLAssociation assoc) throws GenerationException { UMLAssociationEnd otherEnd = getOtherEnd(klass, assoc.getAssociationEnds()); StringBuilder doc = new StringBuilder(); doc.append("/**"); doc.append("\n * Retrieves the value of the "+otherEnd.getRoleName()+" attribute"); doc.append("\n * @return ").append(otherEnd.getRoleName()); doc.append("\n **/\n"); return doc.toString(); } public String getSetterMethodJavaDocs(UMLClass klass, UMLAssociation assoc) throws GenerationException { UMLAssociationEnd otherEnd = getOtherEnd(klass, assoc.getAssociationEnds()); StringBuilder doc = new StringBuilder(); doc.append("/**"); doc.append("\n * Sets the value of "+otherEnd.getRoleName()+" attribute"); doc.append("\n **/\n"); return doc.toString(); } public String reversePackageName(String s) { StringTokenizer st = new StringTokenizer(s,"."); Vector<String> myVector = new Vector<String>(); StringBuilder myStringBuilder = new StringBuilder(); while (st.hasMoreTokens()) { String t = st.nextToken(); myVector.add(t); } for (int i = myVector.size(); i>0; i myStringBuilder.append(myVector.elementAt(i-1)); myStringBuilder.append(Constant.DOT); } int length1 = myStringBuilder.length(); String finalString1 = myStringBuilder.substring(0,length1-1); return finalString1; } public String getWSDDServiceValue(Collection<UMLClass> classColl)throws GenerationException{ StringBuilder nn1 = new StringBuilder(); for(UMLClass klass:classColl){ String pkgName = getFullPackageName(klass); nn1.append(pkgName) .append(Constant.DOT) .append(klass.getName()) .append(Constant.COMMA); } // remove last Comma return nn1.substring(0, nn1.length()-1); } public UMLClass findCollectionTable(UMLAttribute attr, UMLModel model) throws GenerationException { String tableName = getTagValue(attr.getTaggedValues(),TV_MAPPED_COLLECTION_TABLE, 1); UMLClass collectionTable = ModelUtil.findClass(model,BASE_PKG_DATA_MODEL+"."+tableName); if(collectionTable == null) throw new GenerationException("No collection table found named : \""+tableName+"\""); return collectionTable; } public String getCollectionKeyColumnName(UMLClass table,UMLClass klass, UMLAttribute attr) throws GenerationException { return getColumnName(table,TV_MAPPED_ATTR_COLUMN,getFQCN(klass) +"."+ attr.getName(),false,1,1); } public String getCollectionElementColumnName(UMLClass table,UMLClass klass, UMLAttribute attr) throws GenerationException { return getColumnName(table,TV_MAPPED_ELEMENT_COLUMN,getFQCN(klass) +"."+ attr.getName(),false,1,1); } public String getCollectionElementHibernateType(UMLClass klass, UMLAttribute attr) throws GenerationException { String name = getDataType(attr); if(name.startsWith("Collection<")) { name = name.substring("Collection<".length()); name = name.substring(0,name.length()-1); if("int".equalsIgnoreCase(name) || "integer".equalsIgnoreCase(name)) return "integer"; if("double".equalsIgnoreCase(name)) return "double"; if("float".equalsIgnoreCase(name)) return "float"; if("long".equalsIgnoreCase(name)) return "long"; if("string".equalsIgnoreCase(name)) return "string"; if("char".equalsIgnoreCase(name) || "character".equalsIgnoreCase(name)) return "character"; if("boolean".equalsIgnoreCase(name) ) return "boolean"; if("byte".equalsIgnoreCase(name) ) return "byte"; if("short".equalsIgnoreCase(name) ) return "short"; } return name; } public String getJaxbXmlAttributeAnnotation(UMLClass klass, UMLAttribute attr) throws GenerationException{ String type = this.getDataType(attr); log.debug("* * * datatype for attribute " + attr.getName()+": " + type); String collectionType = ""; StringBuffer sb = new StringBuffer(); if (type.startsWith("Collection")){ collectionType = type.substring(type.indexOf("<")+1,type.indexOf(">")); sb.append(" @XmlElementWrapper(name=\""); sb.append(attr.getName()).append("\", "); sb.append("namespace=\"").append(this.getNamespaceUriPrefix() + this.getFullPackageName(klass)).append("\")"); sb.append(" @XmlElement(name=\""); sb.append(collectionType.toLowerCase()).append("\", "); sb.append("namespace=\"").append(this.getNamespaceUriPrefix() + this.getFullPackageName(klass)).append("\")"); log.debug("Collection Attribute @XmlElement annotation: "+sb.toString()); return sb.toString(); } if(isISO21090Enabled){ String isoDatatypeValue = isoDatatypeMap.get(attr.getDatatype().getName()); if (!isJavaDataType(attr)) { log.debug("* * * Detected attribute " + attr.getName()+" is of ISO Datatype: " + isoDatatypeValue); sb.append(" @XmlElement(namespace=\"").append(getNamespaceUriPrefix()).append(getFullPackageName(klass)).append("\")"); if(isIvlDataType(attr)) { String ivlDataType = getIvlDataType(attr); if("PQ".equals(ivlDataType)) sb.append(" @XmlJavaTypeAdapter(JAXBISOIvlPqAdapter.class)"); else if("REAL".equals(ivlDataType)) sb.append(" @XmlJavaTypeAdapter(JAXBISOIvlRealAdapter.class)"); else if("TS".equals(ivlDataType)) sb.append(" @XmlJavaTypeAdapter(JAXBISOIvlTsAdapter.class)"); else if("INT".equals(ivlDataType)) sb.append(" @XmlJavaTypeAdapter(JAXBISOIvlIntAdapter.class)"); else throw new GenerationException("Invalid Ivl type defined: " + attr.getDatatype().getName()); } else { sb.append(" @XmlJavaTypeAdapter(JAXBISOAdapter.class)"); } return sb.toString(); } } return " @XmlAttribute"; } public String getJaxbXmlRootElementAnnotation(UMLClass klass){ StringBuffer sb = new StringBuffer(); sb.append("@XmlRootElement(name=\""); sb.append(klass.getName()).append("\", "); sb.append("namespace=\"").append(this.getNamespaceUriPrefix() + this.getFullPackageName(klass)).append("\")"); log.debug("@XmlRootElement annotation for class "+klass.getName()+": "+sb.toString()); return sb.toString(); } public String getJaxbXmlTypeAnnotation(UMLClass klass){ StringBuffer sb = new StringBuffer("@XmlType(name = \"").append(klass.getName()); sb.append("\", namespace=\""); sb.append(this.getNamespaceUriPrefix() + this.getFullPackageName(klass)); sb.append("\", propOrder = {"); int counter = 0; int totalAttrCount = klass.getAttributes().size(); for(UMLAttribute attr:klass.getAttributes()){ counter++; sb.append("\"").append(attr.getName()).append("\""); if (counter < totalAttrCount){ sb.append(", "); } } counter = 0; int totalAssocCount = klass.getAssociations().size(); if ((totalAttrCount > 0) && (totalAssocCount > 0)){ sb.append(", "); } for(UMLAssociation assoc:klass.getAssociations()){ List<UMLAssociationEnd> assocEnds = assoc.getAssociationEnds(); try { UMLAssociationEnd otherEnd = this.getOtherEnd(klass,assocEnds); counter++; if(otherEnd.isNavigable()) { sb.append("\"").append(otherEnd.getRoleName()).append("\""); if (counter < totalAssocCount){ sb.append(", "); } } } catch (GenerationException e) { log.error("Error generating XML Type Property order for association role name: "+assoc.getRoleName(),e); } } char c = sb.charAt(sb.length()-2); log.debug("Last propOrder char: " +c); if ( c==',' ){ sb.deleteCharAt(sb.length()-2); } sb.append("})"); log.debug("@XMLType string for class " + klass.getName() + sb.toString() ); return sb.toString(); } public String getJaxbXmlAccessorTypeAnnotation(){ return "@XmlAccessorType(XmlAccessType.NONE)"; } public String getJaxbOnCycleDetectedMethod() { StringBuffer sb = new StringBuffer(" public Object onCycleDetected(Context arg0) {\n"); sb.append(" return null;\n"); sb.append(" }\n"); return sb.toString(); } public String getJaxbXmlSeeAlsoAnnotation(UMLClass klass){ List<UMLClass> subClasses = getNonImplicitSubclasses(klass); List<UMLClass> superClasses = getNonImplicitSuperclasses(klass); StringBuffer sb = new StringBuffer(); boolean found = false; if (!subClasses.isEmpty()){ int counter = 0; int totalCount = subClasses.size(); for (UMLClass subKlass:subClasses){ counter++; found = true; sb.append(getFullPackageName(subKlass)+"."+subKlass.getName()+".class"); if (counter < totalCount){ sb.append(", "); } } } if (!superClasses.isEmpty()){ int counter = 0; int totalCount = superClasses.size(); if(found) sb.append(","); for (UMLClass superKlass:superClasses){ counter++; found = true; sb.append(getFullPackageName(superKlass)+"."+superKlass.getName()+".class"); if (counter < totalCount){ sb.append(", "); } } } if(found) { StringBuffer sbreturn = new StringBuffer("@XmlSeeAlso({"); sbreturn.append(sb.toString()); sbreturn.append("})"); log.debug("@XMLSeeAlso string for class " + klass.getName() + sb.toString() ); return sbreturn.toString(); } return ""; } public List<UMLClass> getNonImplicitSuperclasses(UMLClass implicitKlass){ ArrayList<UMLClass> nonImplicitSuperclasses = new ArrayList<UMLClass>(); getNonImplicitSuperclasses(implicitKlass, nonImplicitSuperclasses); return nonImplicitSuperclasses; } private void getNonImplicitSuperclasses(UMLClass klass, ArrayList<UMLClass> nonImplicitSuperclasses){ for(UMLGeneralization gen:klass.getGeneralizations()){ UMLClass superKlass = (UMLClass)gen.getSupertype(); if(superKlass!=klass && isSuperclass(superKlass)){ if(!nonImplicitSuperclasses.contains(superKlass)){ nonImplicitSuperclasses.add(superKlass); } } if(superKlass!=klass) getNonImplicitSuperclasses(superKlass, nonImplicitSuperclasses); } } public List<UMLClass> getNonImplicitSubclasses(UMLClass implicitKlass){ ArrayList<UMLClass> nonImplicitSubclasses = new ArrayList<UMLClass>(); getNonImplicitSubclasses(implicitKlass, nonImplicitSubclasses); return nonImplicitSubclasses; } private void getNonImplicitSubclasses(UMLClass klass, ArrayList<UMLClass> nonImplicitSubclasses){ for(UMLGeneralization gen:klass.getGeneralizations()){ UMLClass subKlass = (UMLClass)gen.getSubtype(); if(subKlass!=klass && !isImplicitParent(subKlass)){ nonImplicitSubclasses.add(subKlass); } if(subKlass!=klass) getNonImplicitSubclasses(subKlass, nonImplicitSubclasses); } } /** * Scans the tag values of the association to determine the cascade-style * * @param association * @param model * @param klass * @return * @throws GenerationException */ public String findCascadeStyle(UMLClass klass, String roleName, UMLAssociation association) throws GenerationException { for (String cascadeStyles : getTagValues(association, TV_NCI_CASCADE_ASSOCIATION + "#" + getFQCN(klass)+"."+roleName)){ List<String> validCascadeStyles = new ArrayList<String>(); for(String cascadeStyle:cascadeStyles.split(",")){ validCascadeStyles.add(cascadeStyle.trim()); } StringBuilder validCascadeStyleSB = new StringBuilder(); validCascadeStyleSB.append(validCascadeStyles.get(0)); for (int i = 1; i <validCascadeStyles.size(); i++ ){ validCascadeStyleSB.append(",").append(validCascadeStyles.get(i)); } return validCascadeStyleSB.toString(); } return "none"; } public String isFKAttributeNull(UMLAssociationEnd otherEnd) { if (otherEnd.getLowMultiplicity() == 0) { return "false"; } return "true"; } /** * Scans the tag values of the association to determine the cascade-style * * @param klass * @param roleName * @param association * @return * @throws GenerationException */ public boolean isLazyLoad(UMLClass klass, String roleName, UMLAssociation association) throws GenerationException { for( String eagerLoadValue : getTagValues(association, TV_NCI_EAGER_LOAD + "#" +getFQCN(klass)+"."+roleName)){ if ("true".equalsIgnoreCase(eagerLoadValue) || "yes".equalsIgnoreCase(eagerLoadValue) ){ return false; } } return true; } /** * Scans the tag values of the association to determine the cascade-style * * @param association * @param model * @param klass * @return * @throws GenerationException */ public Map<String,String> getValidCascadeStyles(){ return CASCADE_STYLES; } /** * Scans the tag values of the association to determine whether or not an inverse-of tag * is present in any of the table columns * * @param klass * @param key * @return * @throws GenerationException */ public List findInverseSettingColumns(UMLClass klass) throws GenerationException { List<String> attrs = new ArrayList<String>(); for(UMLAttribute attr: klass.getAttributes()) { for(UMLTaggedValue tv: attr.getTaggedValues()) { if (TV_INVERSE_ASSOC_COLUMN.equals(tv.getName())) { attrs.add(attr.getName()); } } } return attrs; } public String getHibernateValidatorConstraints(UMLClass klass){ ValidatorClass vClass = vModel.getClass(getFQCN(klass)); ValidatorClass vClassExtension = vModelExtension.getClass(getFQCN(klass)); String constraintAnnotationString=""; if (vClass != null) constraintAnnotationString = "\t" + vClass.getConstraintAnnotationString()+"\n"; if (vClassExtension != null) constraintAnnotationString += "\t" + vClassExtension.getConstraintAnnotationString()+"\n"; return constraintAnnotationString; } public String getHibernateValidatorConstraints(UMLClass klass,UMLAttribute attr){ ValidatorClass vClass = vModel.getClass(getFQCN(klass)); ValidatorClass vClassExtension = vModelExtension.getClass(getFQCN(klass)); List<String> cadsrConstraintAnnotations=new ArrayList<String>(); List<String> userConstraintAnnotations=new ArrayList<String>(); ValidatorAttribute vAttr=null; if (vClass != null) vAttr=vClass.getAttribute(attr.getName()); if (vAttr!=null) cadsrConstraintAnnotations.addAll(vAttr.getConstraintAnnotations()); ValidatorAttribute vAttrExtension=null; if (vClassExtension != null) vAttrExtension=vClassExtension.getAttribute(attr.getName()); if (vAttrExtension!=null) userConstraintAnnotations.addAll(vAttrExtension.getConstraintAnnotations()); //remove duplicates - user constraints override caDSR constraints List<String> constraintAnnotations=new ArrayList<String>(); for(String cadsrConstraintAnnotation : cadsrConstraintAnnotations){ String cadsrConstraintPrefix = cadsrConstraintAnnotation.indexOf("(") > 0 ? cadsrConstraintAnnotation.substring(0, cadsrConstraintAnnotation.indexOf("(")) : cadsrConstraintAnnotation; boolean duplicateConstraint = false; for(String userConstraintAnnotation : userConstraintAnnotations){ if (userConstraintAnnotation.startsWith(cadsrConstraintPrefix)){ duplicateConstraint = true; break; } } if (!duplicateConstraint) constraintAnnotations.add(cadsrConstraintAnnotation); } constraintAnnotations.addAll(userConstraintAnnotations); //Handle special @Patterns scenario List<String> patternConstraintAnnotations=new ArrayList<String>(); for(String constraintAnnotation : constraintAnnotations){ if (constraintAnnotation.indexOf("Pattern")>0){ patternConstraintAnnotations.add(constraintAnnotation); } } StringBuilder sb; if (!patternConstraintAnnotations.isEmpty()){ sb = new StringBuilder(); constraintAnnotations.removeAll(patternConstraintAnnotations); sb.append(patternConstraintAnnotations.remove(0)); for (String patternConstraintAnnotation:patternConstraintAnnotations){ sb.append(",").append(patternConstraintAnnotation); } constraintAnnotations.add("@Patterns({"+sb.toString()+"})"); } sb = new StringBuilder(); for(String constraintAnnotation: constraintAnnotations){ sb.append("\n\t").append(constraintAnnotation); } return sb.toString(); } public Collection<String> getXSDRestrictionValues(UMLClass klass,UMLAttribute attr){ ValidatorClass vClass = vModel.getClass(getFQCN(klass)); ValidatorClass vClassExtension = vModelExtension.getClass(getFQCN(klass)); ArrayList<String> permissibleValues = new ArrayList<String>(); //get user supplied permissible value collection from validator extension file ValidatorAttribute vAttrExtension=null; if (vClassExtension != null) vAttrExtension = vClassExtension.getAttribute(attr.getName()); if (vAttrExtension != null) permissibleValues.addAll(vAttrExtension.getXSDRestrictionCollection()); //user supplied constraints override caDSR constraints, so only retrieve //caDSR constraints if user did not supply any constraints if (permissibleValues.isEmpty()){ ValidatorAttribute vAttr=null; if (vClass != null) vAttr = vClass.getAttribute(attr.getName()); if (vAttr != null) permissibleValues.addAll(vAttr.getXSDRestrictionCollection()); } return permissibleValues; } private Collection<String> getHibernateValidatorConstraintImports(UMLClass klass){ ValidatorClass vClass = vModel.getClass(getFQCN(klass)); ValidatorClass vClassExtension = vModelExtension.getClass(getFQCN(klass)); Collection<String> constraintImports = new HashSet<String>(); if (vClass != null) constraintImports.addAll(vClass.getConstraintImports()); if (vClassExtension != null) constraintImports.addAll(vClassExtension.getConstraintImports()); if (constraintImports.contains("org.hibernate.validator.Pattern")) constraintImports.add("org.hibernate.validator.Patterns"); return constraintImports; } public String getNamespace(UMLTaggableElement te) throws GenerationException { String gmeNamespacePrefix = null; try { gmeNamespacePrefix = getTagValue(te,TV_NCI_GME_XML_NAMESPACE,null,0,1); } catch(GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME 'NCI_GME_XML_NAMESPACE' tag value for element", ge); } return gmeNamespacePrefix; } public String getGMENamespace(UMLClass klass) throws GenerationException{ String gmeNamespace = null; try { gmeNamespace = getNamespace(klass); if (gmeNamespace!=null && gmeNamespace.length()>0) return gmeNamespace; } catch(GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME namespace for: " + getFQEN(klass), ge); } gmeNamespace=getGMENamespace(klass.getPackage()); if (gmeNamespace!=null && gmeNamespace.length()>0) return gmeNamespace; log.error("GME Namespace name not found for: "+getFullPackageName(klass)+". Returning null"); return null; } public String getGMENamespace(UMLPackage pkg) throws GenerationException{ if (pkg==null) return null; log.debug("Getting Package Namespace for: " +pkg.getName()); String gmeNamespace = getNamespace(pkg); if (gmeNamespace!=null && gmeNamespace.length()>0) return gmeNamespace; return getGMENamespace(pkg.getParent()); } public boolean hasGMEXMLNamespaceTag(UMLTaggableElement te){ try { getTagValue(te,TV_NCI_GME_XML_NAMESPACE,null,0,0); } catch (GenerationException e) { return true; } return false; } private String getNamespacePackageName(UMLTaggableElement te) throws GenerationException { String gmeNamespace = null; try { gmeNamespace = getTagValue(te,TV_NCI_GME_XML_NAMESPACE,null,0,1); } catch(GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME 'NCI_GME_XML_NAMESPACE' tag value for: " + getFQEN(te), ge); } if (gmeNamespace != null && gmeNamespace.lastIndexOf('/')<0) throw new GenerationException("Invalid GME Namespace found for:" + getFQEN(te)+": "+gmeNamespace); if (gmeNamespace!=null){ return gmeNamespace.substring(gmeNamespace.lastIndexOf('/')+1, gmeNamespace.length()); } return null; } public String getModelNamespace(UMLModel model, String basePkgLogicalModel) throws GenerationException { //override codegen.properties NAMESPACE_PREFIX property with GME namespace tag value, if it exists StringTokenizer tokenizer = new StringTokenizer(basePkgLogicalModel, "."); UMLPackage pkg=null; if(tokenizer.hasMoreTokens()){ pkg = model.getPackage(tokenizer.nextToken()); while(pkg!=null && tokenizer.hasMoreTokens()){ pkg = pkg.getPackage(tokenizer.nextToken()); } } if (pkg==null){ throw new GenerationException("Error getting the Logical Model package for model: " + pkg.getName()+". Make sure the LOGICAL_MODEL property in codegen.properties file is valid."); } if (pkg!=null){ log.debug("* * * pkgName: " + pkg.getName()); try { String modelNamespacePrefix = this.getNamespace(pkg); log.debug("* * * modelNamespacePrefix: " + modelNamespacePrefix); if (modelNamespacePrefix != null) { if (!modelNamespacePrefix.endsWith("/")) modelNamespacePrefix=modelNamespacePrefix+"/"; return modelNamespacePrefix.replace(" ", "_"); } } catch (GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME Namespace value for model: " + pkg.getName() + ge.getMessage()); } } return null; } public String getNamespacePrefix(UMLPackage pkg) throws GenerationException { String gmeNamespace = null; try { gmeNamespace = getTagValue(pkg,TV_NCI_GME_XML_NAMESPACE,null,0,1); } catch(GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME 'NCI_GME_XML_NAMESPACE' tag value for UML package: " + getFullPackageName(pkg), ge); } if (gmeNamespace != null && gmeNamespace.lastIndexOf('/')<0) throw new GenerationException("Invalid GME Namespace found for UML package " + getFullPackageName(pkg)+": "+gmeNamespace); if (gmeNamespace!=null){ return gmeNamespace.substring(0,gmeNamespace.lastIndexOf('/')); } return null; } public String getXMLClassName(UMLClass klass) throws GenerationException { try { return getTagValue(klass,TV_NCI_GME_XML_ELEMENT,null,0,1); } catch(GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME 'NCI_GME_XML_ELEMENT' tag value for klass: " + klass.getName(), ge); } } public boolean hasGMEXMLClassTag(UMLTaggableElement te){ try { getTagValue(te,TV_NCI_GME_XML_ELEMENT,null,0,0); } catch (GenerationException e) { return true; } return false; } public String getXMLAttributeName(UMLAttribute attr)throws GenerationException{ try { String attributeName = getTagValue(attr,TV_NCI_GME_XML_LOC_REF,null,0,1); if (attributeName !=null && attributeName.length()>0 && (attributeName.startsWith("@"))) attributeName=attributeName.substring(1); //remove leading '@' character return attributeName; } catch(GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME 'NCI_GME_XML_LOC_REF' tag value for attribute: " + attr.getName(), ge); } } public boolean generateXMLAttributeAsElement(UMLAttribute attr)throws GenerationException{ try { String attributeName = getTagValue(attr,TV_NCI_GME_XML_LOC_REF,null,0,1); if (attributeName !=null && attributeName.length()>0 && !(attributeName.startsWith("@"))) return true; return false; } catch(GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME 'NCI_GME_XML_LOC_REF' tag value for attribute: " + attr.getName(), ge); } } public boolean hasGMEXMLAttributeTag(UMLTaggableElement te){ try { getTagValue(te,TV_NCI_GME_XML_LOC_REF,null,0,0); } catch (GenerationException e) { return true; } return false; } public String getXMLLocRef(UMLAssociationEnd assocEnd, String klassName)throws GenerationException { try { return getGmeLocRef(assocEnd.getOwningAssociation(),klassName); } catch(GenerationException ge) { log.error("ERROR: ", ge); throw new GenerationException("Error getting the GME 'NCI_GME_SOURCE_XML_LOC_REF' or 'NCI_GME_TARGET_XML_LOC_REF' tag value for association roleName: " + assocEnd.getRoleName(), ge); } } private String getGmeLocRef(UMLAssociation assoc,String klassName) throws GenerationException { String tv = getTagValue(assoc,TV_NCI_GME_SOURCE_XML_LOC_REF,null,0,1); if (tv !=null && tv.endsWith("/"+klassName)){ return tv.substring(0, tv.lastIndexOf('/')); } tv = getTagValue(assoc,TV_NCI_GME_TARGET_XML_LOC_REF,null,0,1); if (tv !=null && tv.endsWith("/"+klassName)){ return tv.substring(0, tv.lastIndexOf('/')); } return null; } public String getGmeSourceLocRef(UMLAssociation assoc) throws GenerationException { return getTagValue(assoc,TV_NCI_GME_SOURCE_XML_LOC_REF,null,0,1); } public String getGmeTargetLocRef(UMLAssociation assoc) throws GenerationException { return getTagValue(assoc,TV_NCI_GME_TARGET_XML_LOC_REF,null,0,1); } public boolean hasGMELocRefTag(UMLTaggableElement te){ try { getTagValue(te,TV_NCI_GME_SOURCE_XML_LOC_REF,null,0,0); getTagValue(te,TV_NCI_GME_TARGET_XML_LOC_REF,null,0,0); } catch (GenerationException e) { return true; } return false; } public boolean containsIncludedClass(UMLPackage pkg) throws GenerationException { for (UMLClass klass : pkg.getClasses()) { if (isIncluded(klass) && !STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype())){ return true; } } return false; } public String getNamespaceUriPrefix() { return namespaceUriPrefix; } public boolean isUseGMETags() { return useGMETags; } public boolean isJaxbEnabled() { return isJaxbEnabled; } public boolean isISO21090Enabled() { return isISO21090Enabled; } public boolean isJavaDataType(UMLAttribute attr) { String originalType = attr.getDatatype().getName(); if(isISO21090Enabled && isoDatatypeMap.containsKey(originalType)) return false; return javaDatatypeMap.containsKey(originalType.toLowerCase()); } public boolean isIvlDataType(UMLAttribute attr) { String originalType = attr.getDatatype().getName(); if(originalType.startsWith("IVL")) return true; return false; } public String getIvlDataType(UMLAttribute attr) { String originalType = attr.getDatatype().getName(); return originalType.substring(originalType.indexOf("<")+1, originalType.indexOf(">")); } public Collection getSortedByJoinUMLAttribute(UMLClass klass, UMLAttribute idAttribute, UMLClass table) throws GenerationException { List<UMLAttribute> noJoinRequired = new ArrayList<UMLAttribute>(); List<UMLAttribute> joinRequired = new ArrayList<UMLAttribute>(); if (klass.getAttributes().size() > 0) { for (UMLAttribute attr : klass.getAttributes()) { if (attr != idAttribute) { if (isCollection(null, attr)) { noJoinRequired.add(attr); } else if (isJavaDataType(attr)) { noJoinRequired.add(attr); } else // Start ISO Datatype component { IsoDatatypeTransformationHelper isoDatatypeTransformationHelper = new IsoDatatypeTransformationHelper(); isoDatatypeTransformationHelper.setModel(model); isoDatatypeTransformationHelper.setUtils(this); RootNode rootNode = isoDatatypeTransformationHelper.getDatatypeNode(klass, attr, table); if (isoDatatypeTransformationHelper.requiresJoin(rootNode)) joinRequired.add(attr); else noJoinRequired.add(attr); } } } } List<UMLAssociation> noJoinRequiredAssociation = new ArrayList<UMLAssociation>(); List<UMLAssociation> joinRequiredAssociation = new ArrayList<UMLAssociation>(); for(UMLAssociation association:klass.getAssociations()){ List<UMLAssociationEnd> assocEnds = association.getAssociationEnds(); UMLAssociationEnd thisEnd = getThisEnd(klass,assocEnds); UMLAssociationEnd otherEnd = getOtherEnd(klass,assocEnds); if (otherEnd.isNavigable()) { UMLClass assocKlass = (UMLClass) otherEnd.getUMLElement(); if ((isMany2One(thisEnd, otherEnd) || isOne2One(thisEnd, otherEnd)) && null !=findCorrelationTable(association, model, assocKlass, false)) { joinRequiredAssociation.add(association); } else { noJoinRequiredAssociation.add(association); } } } List result = new ArrayList(); result.addAll(noJoinRequired); result.addAll(noJoinRequiredAssociation); result.addAll(joinRequired); result.addAll(joinRequiredAssociation); return result; } public String getHibernateMappingForIsoAttribute(RootNode rootNode, String prefix) throws GenerationException { IsoDatatypeTransformationHelper isoDatatypeTransformationHelper = new IsoDatatypeTransformationHelper(); isoDatatypeTransformationHelper.setModel(model); isoDatatypeTransformationHelper.setUtils(this); StringBuffer buffer = isoDatatypeTransformationHelper.convertToHibernateComponent(rootNode, prefix); return buffer.toString(); } public String getHibernateClassMappingForIsoAttribute(RootNode rootNode, String prefix) throws GenerationException { IsoDatatypeTransformationHelper isoDatatypeTransformationHelper = new IsoDatatypeTransformationHelper(); isoDatatypeTransformationHelper.setModel(model); isoDatatypeTransformationHelper.setUtils(this); StringBuffer buffer = isoDatatypeTransformationHelper.convertToHibernateClass(rootNode, prefix); return buffer.toString(); } public RootNode getDatatypeNode(UMLClass klass, UMLAttribute attribute, UMLClass table) throws GenerationException { IsoDatatypeTransformationHelper isoDatatypeTransformationHelper = new IsoDatatypeTransformationHelper(); isoDatatypeTransformationHelper.setModel(model); isoDatatypeTransformationHelper.setUtils(this); RootNode rootNode = isoDatatypeTransformationHelper.getDatatypeNode(klass, attribute, table); return rootNode; } public boolean isSeperateClassMappingRequired(RootNode rootNode) { IsoDatatypeTransformationHelper isoDatatypeTransformationHelper = new IsoDatatypeTransformationHelper(); isoDatatypeTransformationHelper.setModel(model); isoDatatypeTransformationHelper.setUtils(this); return isoDatatypeTransformationHelper.requiresSeperateClassMapping(rootNode); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1213"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// This file is part of Serleena. // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package com.kyloth.serleena.persistence.sqlite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import java.text.SimpleDateFormat; /** * Supporta la creazione e l'apertura del database SQLite utilizzato * dall'applicazione serleena, secondo quando prescritto dal framework Android. * * @author Filippo Sestini <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="790a1c0a0d101710571f101510090916391e14181015571a1614">[email protected]</a>> * @version 1.0.0 * @since 2015-05-05 */ public class SerleenaDatabase extends SQLiteOpenHelper { public static final String DATABASE_NAME = "serleena.kyloth.db"; public static final String TABLE_EXPERIENCES = "experiences"; public static final String TABLE_TRACKS = "tracks"; public static final String TABLE_TELEMETRIES = "telemetries"; public static final String TABLE_TELEM_EVENTS_HEART_CHECKP = "telemetry_events_heart_checkp"; public static final String TABLE_TELEM_EVENTS_LOCATION = "telemetry_events_location"; public static final String TABLE_RASTER_MAPS = "raster_maps"; public static final String TABLE_CONTACTS = "contacts"; public static final String TABLE_WEATHER_FORECASTS = "weather_forecasts"; public static final String TABLE_USER_POINTS = "user_points"; private static final int DATABASE_VERSION = 1; public static final String EVENT_TYPE_HEARTRATE = "event_heartrate"; public static final String EVENT_TYPE_CHECKPOINT = "event_checkpoint"; public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); private static final String CREATE_TABLE_EXPERIENCES = "CREATE TABLE " + TABLE_EXPERIENCES + "(" + "experience_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "experience_name TEXT NOT NULL)"; private static final String CREATE_TABLE_TRACKS = "CREATE TABLE " + TABLE_TRACKS + "(" + "track_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "track_name TEXT NOT NULL, " + "track_experience INTEGER NOT NULL, " + "FOREIGN KEY(track_experience) REFERENCES experiences(experience_id))"; private static final String CREATE_TABLE_TELEMETRIES = "CREATE TABLE " + TABLE_TELEMETRIES + "(" + "telem_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "telem_track INTEGER NOT NULL, " + "FOREIGN KEY(telem_track) REFERENCES tracks(track_id))"; private static final String CREATE_TABLE_TELEM_EVENTS_LOCATION = "CREATE TABLE " + TABLE_TELEM_EVENTS_LOCATION + "(" + "eventl_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "eventl_timestamp TEXT NOT NULL, " + "eventl_latitude REAL NOT NULL, " + "eventl_longitude REAL NOT NULL, " + "eventl_telem INTEGER NOT NULL, " + "FOREIGN KEY(eventl_telem) REFERENCES telemetries(telem_id))"; private static final String CREATE_TABLE_TELEM_EVENTS_HEART_CHECKP = "CREATE TABLE " + TABLE_TELEM_EVENTS_HEART_CHECKP + "(" + "eventhc_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "eventhc_timestamp TEXT NOT NULL, " + "eventhc_value INTEGER NOT NULL, " + "eventhc_type TEXT NOT NULL, " + "eventhc_telem INTEGER NOT NULL, " + "FOREIGN KEY(eventhc_telem) REFERENCES telemetries(telem_id))"; private static final String CREATE_TABLE_RASTER_MAPS = "CREATE TABLE " + TABLE_RASTER_MAPS + "(" + "raster_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "raster_path TEXT NOT NULL, " + "raster_ne_corner_latitude REAL NOT NULL, " + "raster_ne_corner_longitude REAL NOT NULL, " + "raster_sw_corner_latitude REAL NOT NULL, " + "raster_sw_corner_longitude REAL NOT NULL)"; private static final String CREATE_TABLE_CONTACTS = "CREATE TABLE " + TABLE_CONTACTS + "(" + "contact_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "contact_name TEXT NOT NULL, " + "contact_value TEXT NOT NULL, " + "contact_ne_corner_latitude REAL NOT NULL, " + "contact_ne_corner_longitude REAL NOT NULL, " + "contact_sw_corner_latitude REAL NOT NULL, " + "contact_sw_corner_longitude REAL NOT NULL)"; private static final String CREATE_TABLE_WEATHER_FORECASTS = "CREATE TABLE " + TABLE_WEATHER_FORECASTS + "(" + "weather_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "weather_start INTEGER NOT NULL, " + "weather_end INTEGER INTEGER NULL, " + "weather_condition TEXT NOT NULL, " + "weather_temperature INTEGER NOT NULL, " + "weather_ne_corner_latitude REAL NOT NULL, " + "weather_ne_corner_longitude REAL NOT NULL, " + "weather_sw_corner_latitude REAL NOT NULL, " + "weather_sw_corner_longitude REAL NOT NULL)"; private static final String CREATE_TABLE_USER_POINTS = "CREATE TABLE " + TABLE_USER_POINTS + "(" + "userpoint_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "userpoint_x REAL NOT NULL, " + "userpoint_y REAL NOT NULL, " + "userpoint_experience INTEGER NOT NULL, " + "FOREIGN KEY(userpoint_experience) REFERENCES " + "experiences(experience_id))"; /** * Crea un oggetto SerleenaDatabase. * * @param context Oggetto android.content.Context usato per creare o * aprire il database. * @param name Nome del database. * @param factory Usato per creare cursori. * @param version Versione del database. */ public SerleenaDatabase(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_EXPERIENCES); db.execSQL(CREATE_TABLE_TRACKS); db.execSQL(CREATE_TABLE_TELEMETRIES); db.execSQL(CREATE_TABLE_TELEM_EVENTS_HEART_CHECKP); db.execSQL(CREATE_TABLE_TELEM_EVENTS_LOCATION); db.execSQL(CREATE_TABLE_RASTER_MAPS); db.execSQL(CREATE_TABLE_CONTACTS); db.execSQL(CREATE_TABLE_WEATHER_FORECASTS); db.execSQL(CREATE_TABLE_USER_POINTS); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_EXPERIENCES); db.execSQL("DROP TABLE IF EXISTS " + TABLE_TRACKS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_TELEMETRIES); db.execSQL("DROP TABLE IF EXISTS " + TABLE_TELEM_EVENTS_HEART_CHECKP); db.execSQL("DROP TABLE IF EXISTS " + TABLE_TELEM_EVENTS_LOCATION); db.execSQL("DROP TABLE IF EXISTS " + TABLE_RASTER_MAPS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_WEATHER_FORECASTS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER_POINTS); onCreate(db); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1214"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.ctrip.xpipe.service.sso; import com.google.common.base.Strings; import com.google.common.collect.Maps; import com.ctrip.xpipe.api.config.Config; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.boot.context.embedded.ServletContextInitializer; import org.springframework.boot.context.embedded.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.EventListener; import java.util.Map; import javax.servlet.Filter; import javax.servlet.ServletContext; import javax.servlet.ServletException; /** * @author lepdou 2016-11-08 */ @Configuration public class SSOConfigurations { public static final String KEY_CAS_REGISTER_SERVER_NAME = "cas.register.server.name"; public static final String KEY_CAS_SERVER_LOGIN_URL = "cas.server.login.url"; public static final String KEY_CAS_SERVER_URL_PREFIX = "cas.server.url.prefix"; public static final String KEY_CLOGGING_SERVER_URL = "clogging.server.url"; public static final String KEY_CLOGGING_SERVER_PORT = "clogging.server.port"; public static final String KEY_CREDIS_SERVER_URL = "credis.server.url"; private Config config = Config.DEFAULT; @Bean public ServletListenerRegistrationBean redisAppSettingListener() { ServletListenerRegistrationBean redisAppSettingListener = new ServletListenerRegistrationBean(); redisAppSettingListener.setListener(listener("org.jasig.cas.client.credis.CRedisAppSettingListner")); return redisAppSettingListener; } @Bean public ServletListenerRegistrationBean singleSignOutHttpSessionListener() { ServletListenerRegistrationBean singleSignOutHttpSessionListener = new ServletListenerRegistrationBean(); singleSignOutHttpSessionListener .setListener(listener("org.jasig.cas.client.session.SingleSignOutHttpSessionListener")); return singleSignOutHttpSessionListener; } @Bean public FilterRegistrationBean casFilter() { FilterRegistrationBean singleSignOutFilter = new FilterRegistrationBean(); singleSignOutFilter.setFilter(filter("org.jasig.cas.client.session.SingleSignOutFilter"));</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1215"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.ensipoly.match3.activities; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayout; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.ensipoly.match3.R; import com.ensipoly.match3.fragments.GameMenuFragment; import com.ensipoly.match3.models.Direction; import com.ensipoly.match3.models.Grid; import com.ensipoly.match3.models.Token; import com.ensipoly.match3.models.events.AddEvent; import com.ensipoly.match3.models.events.EndEvent; import com.ensipoly.match3.models.events.EventAcceptor; import com.ensipoly.match3.models.events.EventVisitor; import com.ensipoly.match3.models.events.MoveEvent; import com.ensipoly.match3.models.events.RemoveEvent; import com.ensipoly.match3.models.events.ScoreEvent; import com.ensipoly.match3.models.events.SwapEvent; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Observable; import java.util.Observer; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class GameActivity extends AppCompatActivity implements Observer, EventVisitor { private static final String TAG = "GameActivity"; private String SCORE; private String TURNS; private String MINSCORE; private String COMBO; private TextView scoreTextView; private TextView turnsTextView; private TextView minScoreTextView; private TextView comboTextView; private Grid grid = null; private GridLayout gridLayout = null; private Queue<EventAcceptor> listEvents = new ConcurrentLinkedQueue<>(); private boolean addList; private int turnsLeft; private int minScore; private int score; private int combo; private int level; FloatingActionMenu menu; private SharedPreferences sharedPref; private FloatingActionButton joker; private static final int MAX_LEVELS=4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); level = getIntent().getIntExtra(GameMenuFragment.LEVEL, 1); sharedPref = getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE); menu = (FloatingActionMenu) findViewById(R.id.fab_menu); menu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() { @Override public void onMenuToggle(boolean opened) { setClickable(!opened); if (opened) findViewById(R.id.overlay).setVisibility(View.VISIBLE); else findViewById(R.id.overlay).setVisibility(View.GONE); } }); findViewById(R.id.restart).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { menu.close(true); joker.setVisibility(View.VISIBLE); joker.setLabelVisibility(View.VISIBLE); listEvents.clear(); initialize(true); } }); findViewById(R.id.quit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { menu.close(true); joker.setVisibility(View.VISIBLE); joker.setLabelVisibility(View.VISIBLE); listEvents.clear(); onBackPressed(); } }); joker = (FloatingActionButton) findViewById(R.id.joker); joker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { menu.close(true); listEvents.clear(); initialize(false); } }); SCORE = getString(R.string.score); TURNS = getString(R.string.turns_left); MINSCORE = getString(R.string.min_score); COMBO = getString(R.string.combo); scoreTextView = (TextView) findViewById(R.id.score_text); minScoreTextView = (TextView) findViewById(R.id.min_score_text); turnsTextView = (TextView) findViewById(R.id.turns_left_text); comboTextView = (TextView) findViewById(R.id.combo_text); initialize(true); } @Override public void onBackPressed() { if(turnsLeft==0) { super.onBackPressed(); return; } if(menu.isOpened()){ menu.close(true); return; } new AlertDialog.Builder(this) .setIcon(R.drawable.ic_warning_black_24dp) .setTitle(getString(R.string.quit_alert_title)) .setMessage(getString(R.string.quit_alert_body)) .setPositiveButton(getString(R.string.quit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { GameActivity.super.onBackPressed(); } }) .setNegativeButton(getString(R.string.cancel), null) .show(); } /** * Helper functions **/ private GradientDrawable getDrawable(Token token) { GradientDrawable shape = new GradientDrawable(); shape.setShape(GradientDrawable.OVAL); shape.setColor(Color.parseColor(token.toString())); return shape; } private void setClickable(boolean clickable) { for (int i = 0; i < gridLayout.getChildCount(); i++) gridLayout.getChildAt(i).setLongClickable(clickable); } private int convert(int x, int y) { return x * grid.getColumnCount() + y; } private void initGame() { combo = 1; switch (level) { case 1: turnsLeft = 6; minScore = 800; break; case 2: turnsLeft = 10; minScore = 1200; break; case 3: turnsLeft = 10; minScore = 1400; break; case 4: turnsLeft = 10; minScore = 1800; break; } } private void initGrid() { try { grid = new Grid(new BufferedReader(new InputStreamReader(getAssets().open("level" + level + ".data")))); grid.addObserver(this); if (gridLayout == null) gridLayout = (GridLayout) findViewById(R.id.grid); else gridLayout.removeAllViews(); gridLayout.setRowCount(grid.getRowCount()); gridLayout.setColumnCount(grid.getColumnCount()); for (int x = 0; x < grid.getRowCount(); x++) { for (int y = 0; y < grid.getColumnCount(); y++) { ImageView imageView; // if it's not recycled, initialize some attributes imageView = new ImageView(this); GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.rowSpec = GridLayout.spec(x, 1.0f); params.columnSpec = GridLayout.spec(y, 1.0f); imageView.setLayoutParams(params); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setAdjustViewBounds(true); imageView.setPadding(8, 8, 8, 8); imageView.setImageDrawable(getDrawable(grid.getToken(x, y))); final int xpos = x; final int ypos = y; imageView.setLongClickable(true); imageView.setOnTouchListener(new View.OnTouchListener() { private MyGestureDetector mgd = new MyGestureDetector(xpos, ypos); private GestureDetector gestureDetector = null; @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (gestureDetector == null) gestureDetector = new GestureDetector(GameActivity.this, mgd); return gestureDetector.onTouchEvent(motionEvent); } }); gridLayout.addView(imageView); } } if (grid.isThereAnyCombinationRemaining()) Log.e(TAG, "There is combination"); else Log.e(TAG, "There is no combination"); } catch (IOException e) { e.printStackTrace(); } } private void setGreenText(TextView view, String beginning, String inGreen) { String fullText = beginning + inGreen; Spannable spannable = new SpannableString(fullText); spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#76FF03")), beginning.length(), fullText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); view.setText(spannable, TextView.BufferType.SPANNABLE); } private void updateTextViews() { updateTurnsView(); updateScoreAndComboViews(); } private void updateTurnsView() { turnsTextView.setText(TURNS + " " + turnsLeft); } private void updateScoreAndComboViews() { if (score >= minScore) setGreenText(scoreTextView, SCORE + " ", score + ""); else scoreTextView.setText(SCORE + " " + score); if (combo > 1) setGreenText(comboTextView, COMBO + " ", "x" + combo); else comboTextView.setText(COMBO + " x" + combo); } private void initialize(int level,boolean resetScore){ this.level = level; initialize(resetScore); } private void initialize(boolean resetScore){ if(resetScore) score =0; initGame(); initGrid(); minScoreTextView.setText(MINSCORE + " " + minScore); ((TextView) findViewById(R.id.level_text)).setText(getLevelString()); updateTextViews(); } private String getLevelString(){ switch (level){ case 1: return getString(R.string.level1); case 2: return getString(R.string.level2); case 3: return getString(R.string.level3); case 4: return getString(R.string.level4); default: return ""; } } /** * Visitor functions **/ @Override public void visit(AddEvent add) { if (addList) { listEvents.add(add); } else { int x = add.getX(); int y = add.getY(); Token token = add.getToken(); ImageView view = ((ImageView) gridLayout.getChildAt(convert(x, y))); view.setImageDrawable(getDrawable(token)); view.setVisibility(View.VISIBLE); } } @Override public void visit(RemoveEvent re) { if (addList) { listEvents.add(re); } else { int x = re.getX(); int y = re.getY(); gridLayout.getChildAt(convert(x, y)).setVisibility(View.INVISIBLE); } } @Override public void visit(MoveEvent move) { if (addList) { listEvents.add(move); } else { int prevX = move.getPrevX(); int newX = move.getNewX(); int y = move.getY(); Token prevToken = move.getToken(); ImageView view = ((ImageView) gridLayout.getChildAt(convert(newX, y))); view.setImageDrawable(getDrawable(prevToken)); view.setVisibility(View.VISIBLE); gridLayout.getChildAt(convert(prevX, y)).setVisibility(View.INVISIBLE); } } @Override public void visit(SwapEvent swap) { if (addList) { listEvents.add(swap); } else { int x1 = swap.getX1(); int y1 = swap.getY1(); int x2 = swap.getX2(); int y2 = swap.getY2(); Token t1 = swap.getT1(); Token t2 = swap.getT2(); ImageView view = ((ImageView) gridLayout.getChildAt(convert(x1, y1))); view.setImageDrawable(getDrawable(t2)); view = ((ImageView) gridLayout.getChildAt(convert(x2, y2))); view.setImageDrawable(getDrawable(t1)); } } @Override public void visit(EndEvent end) { if (addList) { addList = false; listEvents.add(end); doEvents(); } else { turnsLeft updateTurnsView(); combo = 1; updateScoreAndComboViews(); if (end.isEndGame() || turnsLeft == 0) { menu.open(true); if(turnsLeft==0) { joker.setLabelVisibility(View.GONE); joker.setVisibility(View.GONE); } }else setClickable(true); if(score>=minScore && level<MAX_LEVELS){ int best= sharedPref.getInt(getString(R.string.best_level),-1); if(best<0) Log.e(TAG,"Unexpected best level"); if (best==level){ SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(R.string.best_level), level+1); editor.apply(); new AlertDialog.Builder(this) .setTitle(getString(R.string.unlock_alert_title)) .setMessage(getString(R.string.unlock_alert_body)) .setPositiveButton(getString(R.string.next_level), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { initialize(level+1,true); } }) .setNegativeButton(getString(R.string.continue_button), null) .show(); } } } } @Override public void visit(ScoreEvent scoreEvent) { if (addList) { listEvents.add(scoreEvent); } else { score += scoreEvent.getScore(); combo = scoreEvent.getCombo(); updateScoreAndComboViews(); } } private void doEvents() { if (listEvents.size() == 0) return; EventAcceptor event = listEvents.poll(); event.accept(this); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { doEvents(); } }, 300); } /** * Observer functions **/ @Override public void update(Observable observable, Object o) { if (o instanceof EventAcceptor) { ((EventAcceptor) o).accept(this); } } /** * Gesture functions **/ class MyGestureDetector extends GestureDetector.SimpleOnGestureListener { private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private int x; private int y; MyGestureDetector(int x, int y) { this.x = x; this.y = y; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Direction dir = null; // right to left swipe if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(GameActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show(); dir = Direction.LEFT; } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(GameActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show(); dir = Direction.RIGHT; } else if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(GameActivity.this, "Up Swipe", Toast.LENGTH_SHORT).show(); dir = Direction.UP; } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(GameActivity.this, "Down Swipe", Toast.LENGTH_SHORT).show(); dir = Direction.DOWN; } if (dir == null) return false; if (grid.isSwapPossible(x, y, dir)) { setClickable(false); addList = true; grid.swapElements(x, y, dir); } else { Toast.makeText(GameActivity.this, "Swap Impossible", Toast.LENGTH_SHORT).show(); } return true; } @Override public boolean onDown(MotionEvent e) { return false; } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1216"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.ensipoly.match3.activities; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayout; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.ensipoly.match3.R; import com.ensipoly.match3.fragments.GameMenuFragment; import com.ensipoly.match3.models.Direction; import com.ensipoly.match3.models.Grid; import com.ensipoly.match3.models.Token; import com.ensipoly.match3.models.events.AddEvent; import com.ensipoly.match3.models.events.EndEvent; import com.ensipoly.match3.models.events.EventAcceptor; import com.ensipoly.match3.models.events.EventVisitor; import com.ensipoly.match3.models.events.MoveEvent; import com.ensipoly.match3.models.events.RemoveEvent; import com.ensipoly.match3.models.events.ScoreEvent; import com.ensipoly.match3.models.events.SwapEvent; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Observable; import java.util.Observer; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class GameActivity extends AppCompatActivity implements Observer, EventVisitor { private static final String TAG = "GameActivity"; private String SCORE; private String TURNS; private String MINSCORE; private String COMBO; private TextView scoreTextView; private TextView turnsTextView; private TextView minScoreTextView; private TextView comboTextView; private Grid grid = null; private GridLayout gridLayout = null; private Queue<EventAcceptor> listEvents = new ConcurrentLinkedQueue<>(); private boolean addList; private int turnsLeft; private int minScore; private int score; private int combo; private int level; FloatingActionMenu menu; private SharedPreferences sharedPref; private FloatingActionButton joker; private static final int MAX_LEVELS=4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); level = getIntent().getIntExtra(GameMenuFragment.LEVEL, 1); sharedPref = getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE); menu = (FloatingActionMenu) findViewById(R.id.fab_menu); menu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() { @Override public void onMenuToggle(boolean opened) { setClickable(!opened); if (opened) findViewById(R.id.overlay).setVisibility(View.VISIBLE); else findViewById(R.id.overlay).setVisibility(View.GONE); } }); findViewById(R.id.restart).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { menu.close(true); joker.setVisibility(View.VISIBLE); joker.setLabelVisibility(View.VISIBLE); listEvents.clear(); initialize(true); } }); findViewById(R.id.quit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { menu.close(true); joker.setVisibility(View.VISIBLE); joker.setLabelVisibility(View.VISIBLE); listEvents.clear(); quitDialog(); } }); joker = (FloatingActionButton) findViewById(R.id.joker); joker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { menu.close(true); listEvents.clear(); initialize(false); } }); SCORE = getString(R.string.score); TURNS = getString(R.string.turns_left); MINSCORE = getString(R.string.min_score); COMBO = getString(R.string.combo); scoreTextView = (TextView) findViewById(R.id.score_text); minScoreTextView = (TextView) findViewById(R.id.min_score_text); turnsTextView = (TextView) findViewById(R.id.turns_left_text); comboTextView = (TextView) findViewById(R.id.combo_text); initialize(true); } @Override public void onBackPressed() { if(turnsLeft==0) { super.onBackPressed(); return; } if(menu.isOpened()){ menu.close(true); return; } quitDialog(); } /** * Helper functions **/ private GradientDrawable getDrawable(Token token) { GradientDrawable shape = new GradientDrawable(); shape.setShape(GradientDrawable.OVAL); shape.setColor(Color.parseColor(token.toString())); return shape; } private void setClickable(boolean clickable) { for (int i = 0; i < gridLayout.getChildCount(); i++) gridLayout.getChildAt(i).setLongClickable(clickable); } private int convert(int x, int y) { return x * grid.getColumnCount() + y; } private void initGame() { combo = 1; switch (level) { case 1: turnsLeft = 6; minScore = 800; break; case 2: turnsLeft = 10; minScore = 1200; break; case 3: turnsLeft = 10; minScore = 1400; break; case 4: turnsLeft = 10; minScore = 1800; break; } } private void initGrid() { try { grid = new Grid(new BufferedReader(new InputStreamReader(getAssets().open("level" + level + ".data")))); grid.addObserver(this); if (gridLayout == null) gridLayout = (GridLayout) findViewById(R.id.grid); else gridLayout.removeAllViews(); gridLayout.setRowCount(grid.getRowCount()); gridLayout.setColumnCount(grid.getColumnCount()); for (int x = 0; x < grid.getRowCount(); x++) { for (int y = 0; y < grid.getColumnCount(); y++) { ImageView imageView; // if it's not recycled, initialize some attributes imageView = new ImageView(this); GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.rowSpec = GridLayout.spec(x, 1.0f); params.columnSpec = GridLayout.spec(y, 1.0f); imageView.setLayoutParams(params); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setAdjustViewBounds(true); imageView.setPadding(8, 8, 8, 8); imageView.setImageDrawable(getDrawable(grid.getToken(x, y))); final int xpos = x; final int ypos = y; imageView.setLongClickable(true); imageView.setOnTouchListener(new View.OnTouchListener() { private MyGestureDetector mgd = new MyGestureDetector(xpos, ypos); private GestureDetector gestureDetector = null; @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (gestureDetector == null) gestureDetector = new GestureDetector(GameActivity.this, mgd); return gestureDetector.onTouchEvent(motionEvent); } }); gridLayout.addView(imageView); } } if (grid.isThereAnyCombinationRemaining()) Log.e(TAG, "There is combination"); else Log.e(TAG, "There is no combination"); } catch (IOException e) { e.printStackTrace(); } } private void setGreenText(TextView view, String beginning, String inGreen) { String fullText = beginning + inGreen; Spannable spannable = new SpannableString(fullText); spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#76FF03")), beginning.length(), fullText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); view.setText(spannable, TextView.BufferType.SPANNABLE); } private void updateTextViews() { updateTurnsView(); updateScoreAndComboViews(); } private void updateTurnsView() { turnsTextView.setText(TURNS + " " + turnsLeft); } private void updateScoreAndComboViews() { if (score >= minScore) setGreenText(scoreTextView, SCORE + " ", score + ""); else scoreTextView.setText(SCORE + " " + score); if (combo > 1) setGreenText(comboTextView, COMBO + " ", "x" + combo); else comboTextView.setText(COMBO + " x" + combo); } private void initialize(int level,boolean resetScore){ this.level = level; initialize(resetScore); } private void initialize(boolean resetScore){ if(resetScore) score =0; initGame(); initGrid(); minScoreTextView.setText(MINSCORE + " " + minScore); ((TextView) findViewById(R.id.level_text)).setText(getLevelString()); updateTextViews(); } private String getLevelString(){ switch (level){ case 1: return getString(R.string.level1); case 2: return getString(R.string.level2); case 3: return getString(R.string.level3); case 4: return getString(R.string.level4); default: return ""; } } private void quitDialog(){ if(turnsLeft==0) { super.onBackPressed(); return; } new AlertDialog.Builder(this) .setIcon(R.drawable.ic_warning_black_24dp) .setTitle(getString(R.string.quit_alert_title)) .setMessage(getString(R.string.quit_alert_body)) .setPositiveButton(getString(R.string.quit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { GameActivity.super.onBackPressed(); } }) .setNegativeButton(getString(R.string.cancel), null) .show(); } /** * Visitor functions **/ @Override public void visit(AddEvent add) { if (addList) { listEvents.add(add); } else { int x = add.getX(); int y = add.getY(); Token token = add.getToken(); ImageView view = ((ImageView) gridLayout.getChildAt(convert(x, y))); view.setImageDrawable(getDrawable(token)); view.setVisibility(View.VISIBLE); } } @Override public void visit(RemoveEvent re) { if (addList) { listEvents.add(re); } else { int x = re.getX(); int y = re.getY(); gridLayout.getChildAt(convert(x, y)).setVisibility(View.INVISIBLE); } } @Override public void visit(MoveEvent move) { if (addList) { listEvents.add(move); } else { int prevX = move.getPrevX(); int newX = move.getNewX(); int y = move.getY(); Token prevToken = move.getToken(); ImageView view = ((ImageView) gridLayout.getChildAt(convert(newX, y))); view.setImageDrawable(getDrawable(prevToken)); view.setVisibility(View.VISIBLE); gridLayout.getChildAt(convert(prevX, y)).setVisibility(View.INVISIBLE); } } @Override public void visit(SwapEvent swap) { if (addList) { listEvents.add(swap); } else { int x1 = swap.getX1(); int y1 = swap.getY1(); int x2 = swap.getX2(); int y2 = swap.getY2(); Token t1 = swap.getT1(); Token t2 = swap.getT2(); ImageView view = ((ImageView) gridLayout.getChildAt(convert(x1, y1))); view.setImageDrawable(getDrawable(t2)); view = ((ImageView) gridLayout.getChildAt(convert(x2, y2))); view.setImageDrawable(getDrawable(t1)); } } @Override public void visit(EndEvent end) { if (addList) { addList = false; listEvents.add(end); doEvents(); } else { turnsLeft updateTurnsView(); combo = 1; updateScoreAndComboViews(); if (end.isEndGame() || turnsLeft == 0) { menu.open(true); if(turnsLeft==0) { joker.setLabelVisibility(View.GONE); joker.setVisibility(View.GONE); } }else setClickable(true); if(score>=minScore && level<MAX_LEVELS){ int best= sharedPref.getInt(getString(R.string.best_level),-1); if(best<0) Log.e(TAG,"Unexpected best level"); if (best==level){ SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(R.string.best_level), level+1); editor.apply(); new AlertDialog.Builder(this) .setTitle(getString(R.string.unlock_alert_title)) .setMessage(getString(R.string.unlock_alert_body)) .setPositiveButton(getString(R.string.next_level), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { initialize(level+1,true); } }) .setNegativeButton(getString(R.string.continue_button), null) .show(); } } } } @Override public void visit(ScoreEvent scoreEvent) { if (addList) { listEvents.add(scoreEvent); } else { score += scoreEvent.getScore(); combo = scoreEvent.getCombo(); updateScoreAndComboViews(); } } private void doEvents() { if (listEvents.size() == 0) return; EventAcceptor event = listEvents.poll(); event.accept(this); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { doEvents(); } }, 300); } /** * Observer functions **/ @Override public void update(Observable observable, Object o) { if (o instanceof EventAcceptor) { ((EventAcceptor) o).accept(this); } } /** * Gesture functions **/ class MyGestureDetector extends GestureDetector.SimpleOnGestureListener { private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private int x; private int y; MyGestureDetector(int x, int y) { this.x = x; this.y = y; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Direction dir = null; // right to left swipe if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(GameActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show(); dir = Direction.LEFT; } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(GameActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show(); dir = Direction.RIGHT; } else if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(GameActivity.this, "Up Swipe", Toast.LENGTH_SHORT).show(); dir = Direction.UP; } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(GameActivity.this, "Down Swipe", Toast.LENGTH_SHORT).show(); dir = Direction.DOWN; } if (dir == null) return false; if (grid.isSwapPossible(x, y, dir)) { setClickable(false); addList = true; grid.swapElements(x, y, dir); } else { Toast.makeText(GameActivity.this, "Swap Impossible", Toast.LENGTH_SHORT).show(); } return true; } @Override public boolean onDown(MotionEvent e) { return false; } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1217"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.intellij.psi; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiSearchHelper; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; /** * @author ven */ public class GenericsUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.GenericsUtil"); public static PsiType getGreatestLowerBound(PsiType type1, PsiType type2) { return PsiIntersectionType.createIntersection(new PsiType[]{type1, type2}); } public static PsiType getLeastUpperBound(PsiType type1, PsiType type2, PsiManager manager) { if (type1 instanceof PsiPrimitiveType || type2 instanceof PsiPrimitiveType) return null; return getLeastUpperBound(type1, type2, new LinkedHashSet<Pair<PsiType, PsiType>>(), manager); } private static PsiType getLeastUpperBound(PsiType type1, PsiType type2, Set<Pair<PsiType, PsiType>> compared, PsiManager manager) { if (type1 instanceof PsiCapturedWildcardType) { return getLeastUpperBound(((PsiCapturedWildcardType)type1).getUpperBound(), type2, compared, manager); } else if (type2 instanceof PsiCapturedWildcardType) { return getLeastUpperBound(type1, ((PsiCapturedWildcardType)type2).getUpperBound(), compared, manager); } if (type1 instanceof PsiArrayType && type2 instanceof PsiArrayType) { final PsiType componentType = getLeastUpperBound(((PsiArrayType)type1).getComponentType(), ((PsiArrayType)type2).getComponentType(), manager); if (componentType != null) { return componentType.createArrayType(); } } else if (type1 instanceof PsiClassType && type2 instanceof PsiClassType) { PsiClassType.ClassResolveResult classResolveResult1 = ((PsiClassType)type1).resolveGenerics(); PsiClassType.ClassResolveResult classResolveResult2 = ((PsiClassType)type2).resolveGenerics(); PsiClass aClass = classResolveResult1.getElement(); PsiClass bClass = classResolveResult2.getElement(); if (aClass == null || bClass == null) { return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", GlobalSearchScope.allScope(manager.getProject())); } PsiClass[] supers = getLeastUpperClasses(aClass, bClass); if (supers.length == 0) { return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", aClass.getResolveScope()); } PsiClassType[] conjuncts = new PsiClassType[supers.length]; for (int i = 0; i < supers.length; i++) { PsiClass aSuper = supers[i]; PsiSubstitutor subst1 = TypeConversionUtil.getSuperClassSubstitutor(aSuper, aClass, classResolveResult1.getSubstitutor()); PsiSubstitutor subst2 = TypeConversionUtil.getSuperClassSubstitutor(aSuper, bClass, classResolveResult2.getSubstitutor()); LOG.assertTrue(subst1 != null && subst2 != null); Iterator<PsiTypeParameter> iterator = PsiUtil.typeParametersIterator(aSuper); PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; while (iterator.hasNext()) { PsiTypeParameter parameter = iterator.next(); PsiType mapping1 = subst1.substitute(parameter); PsiType mapping2 = subst2.substitute(parameter); if (mapping1 != null && mapping2 != null) { substitutor = substitutor.put(parameter, getLeastContainingTypeArgument(mapping1, mapping2, compared, manager)); } else { substitutor = substitutor.put(parameter, null); } } conjuncts[i] = manager.getElementFactory().createType(aSuper, substitutor); } return PsiIntersectionType.createIntersection(conjuncts); } return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", GlobalSearchScope.allScope(manager.getProject())); } private static PsiType getLeastContainingTypeArgument(PsiType type1, PsiType type2, Set<Pair<PsiType, PsiType>> compared, PsiManager manager) { Pair<PsiType, PsiType> p = new Pair<PsiType, PsiType>(type1, type2); if (compared.contains(p)) return PsiWildcardType.createUnbounded(manager); compared.add(p); if (type1 instanceof PsiWildcardType) { PsiWildcardType wild1 = (PsiWildcardType)type1; if (type2 instanceof PsiWildcardType) { PsiWildcardType wild2 = (PsiWildcardType)type2; if (wild1.isExtends() == wild2.isExtends()) { return wild1.isExtends() ? PsiWildcardType.createExtends(manager, getLeastUpperBound(wild1.getBound(), wild2.getBound(), compared, manager)) : wild1.isSuper() ? PsiWildcardType.createSuper(manager, getGreatestLowerBound(wild1.getBound(), wild2.getBound())) : wild1; } else { return wild1.getBound().equals(wild2.getBound()) ? wild1.getBound() : PsiWildcardType.createUnbounded(manager); } } else { return wild1.isExtends() ? PsiWildcardType.createExtends(manager, getLeastUpperBound(wild1.getBound(), type2, compared, manager)) : wild1.isSuper() ? PsiWildcardType.createSuper(manager, getGreatestLowerBound(wild1.getBound(), type2)) : wild1; } } else if (type2 instanceof PsiWildcardType) { return getLeastContainingTypeArgument(type2, type1, compared, manager); } //Done with wildcards if (type1.equals(type2)) return type1; return PsiWildcardType.createExtends(manager, getLeastUpperBound(type1, type2, compared, manager)); } public static PsiClass[] getLeastUpperClasses(PsiClass aClass, PsiClass bClass) { if (InheritanceUtil.isInheritorOrSelf(aClass, bClass, true)) return new PsiClass[]{bClass}; Set<PsiClass> supers = new LinkedHashSet<PsiClass>(); getLeastUpperClassesInner(aClass, bClass, supers); return supers.toArray(new PsiClass[supers.size()]); } private static void getLeastUpperClassesInner(PsiClass aClass, PsiClass bClass, Set<PsiClass> supers) { if (bClass.isInheritor(aClass, true)) { supers.add(aClass); } else { final PsiClass[] aSupers = aClass.getSupers(); for (int i = 0; i < aSupers.length; i++) { PsiClass aSuper = aSupers[i]; getLeastUpperClassesInner(aSuper, bClass, supers); } } } public static boolean isTypeArgumentsApplicable(PsiTypeParameter[] typeParams, PsiSubstitutor substitutor) { for (int i = 0; i < typeParams.length; i++) { PsiTypeParameter typeParameter = typeParams[i]; PsiType substituted = substitutor.substitute(typeParameter); if (substituted == null) return true; PsiClassType[] extendsTypes = typeParameter.getExtendsListTypes(); for (int j = 0; j < extendsTypes.length; j++) { PsiType extendsType = substitutor.substitute(extendsTypes[j]); if (!extendsType.isAssignableFrom(substituted)) { return false; } } } return true; } public static boolean isFromExternalTypeLanguage (PsiType type) { return type.getInternalCanonicalText().equals(type.getCanonicalText()); } public static PsiClass[] getGreatestLowerClasses(final PsiClass aClass, final PsiClass bClass) { if (InheritanceUtil.isInheritorOrSelf(aClass, bClass, true)) { return new PsiClass[]{aClass}; } if (InheritanceUtil.isInheritorOrSelf(bClass, aClass, true)) { return new PsiClass[]{bClass}; } final Set<PsiClass> descendants = new LinkedHashSet<PsiClass>(); new Object() { public void getGreatestLowerClasses(final PsiClass aClass, final PsiClass bClass, final Set<PsiClass> descendants) { if (aClass.isInheritor(bClass, true)) { descendants.add(bClass); } else { final PsiSearchHelper helper = aClass.getManager().getSearchHelper(); final PsiClass[] bSubs = helper.findInheritors(bClass, helper.getAccessScope(bClass), true); for (int i = 0; i < bSubs.length; i++) { getLeastUpperClassesInner(bSubs[i], aClass, descendants); } } } }.getGreatestLowerClasses(aClass, bClass, descendants); return descendants.toArray(new PsiClass[descendants.size()]); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1218"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// This source code is available under agreement available at // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France package org.talend.dataprep.dataset.adapter.conversions; import static org.talend.dataprep.conversions.BeanConversionService.fromBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import org.talend.daikon.exception.TalendRuntimeException; import org.talend.daikon.exception.error.CommonErrorCodes; import org.talend.dataprep.api.dataset.DataSetContent; import org.talend.dataprep.api.dataset.DataSetGovernance; import org.talend.dataprep.api.dataset.DataSetGovernance.Certification; import org.talend.dataprep.api.dataset.DataSetLocation; import org.talend.dataprep.api.dataset.DataSetMetadata; import org.talend.dataprep.conversions.BeanConversionService; import org.talend.dataprep.dataset.adapter.Dataset; import org.talend.dataprep.dataset.adapter.Dataset.CertificationState; import org.talend.dataprep.dataset.adapter.Datastore; import org.talend.dataprep.processor.BeanConversionServiceWrapper; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * Bean Conversion from {@link Dataset} to {@link DataSetMetadata} */ @Component public class DatasetBeanConversion extends BeanConversionServiceWrapper { private static final Logger LOGGER = LoggerFactory.getLogger(DatasetBeanConversion.class); private final ObjectMapper objectMapper; public DatasetBeanConversion(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public BeanConversionService doWith(BeanConversionService conversionService, String beanName, ApplicationContext applicationContext) { conversionService.register(fromBean(Dataset.class) .toBeans(DataSetMetadata.class) .using(DataSetMetadata.class, (dataset, dataSetMetadata) -> { dataSetMetadata.setName(dataset.getLabel()); dataSetMetadata.setCreationDate(dataset.getCreated()); dataSetMetadata.setLastModificationDate(dataset.getUpdated()); dataSetMetadata.setAuthor(dataset.getOwner()); CertificationState certificationState = dataset.getCertification(); if (certificationState != null) { DataSetGovernance governance = new DataSetGovernance(); governance.setCertificationStep(Certification.valueOf(certificationState.name())); dataSetMetadata.setGovernance(governance); } JsonNode datasetProperties = dataset.getProperties(); if (datasetProperties == null) { datasetProperties = objectMapper.createObjectNode(); } Datastore datastore = dataset.getDatastore(); //FIXME bypass for content / location information about local file or live dataset if (datastore == null) { try { if (datasetProperties.has("content")) { DataSetContent content = objectMapper.treeToValue(datasetProperties.get("content"), DataSetContent.class); dataSetMetadata.setContent(content); } else { LOGGER.warn("no dataset content for the dataset [{}]", dataSetMetadata.getId()); } if (datasetProperties.has("location")) { DataSetLocation location = objectMapper.treeToValue(datasetProperties.get("location"), DataSetLocation.class); dataSetMetadata.setLocation(location); } else { LOGGER.warn("no dataset location for the dataset [{}]", dataSetMetadata.getId()); } } catch (JsonProcessingException e) { throw new TalendRuntimeException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e); } } // Manage legacy fields that doesn't match data catalog concept Dataset.DataSetMetadataLegacy dataSetMetadataLegacy = dataset.getDataSetMetadataLegacy(); if (dataSetMetadataLegacy != null) { dataSetMetadata.setSheetName(dataSetMetadataLegacy.getSheetName()); dataSetMetadata.setSchemaParserResult(dataSetMetadataLegacy.getSchemaParserResult()); dataSetMetadata.setDraft(dataSetMetadataLegacy.isDraft()); dataSetMetadata.setEncoding(dataSetMetadataLegacy.getEncoding()); dataSetMetadata.setTag(dataSetMetadataLegacy.getTag()); } return dataSetMetadata; }) .build()); return conversionService; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1219"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.hisp.dhis.analytics; import com.google.common.base.MoreObjects; import org.hisp.dhis.util.DateUtils; import org.hisp.dhis.calendar.Calendar; import org.hisp.dhis.calendar.DateTimeUnit; import org.hisp.dhis.period.PeriodType; import org.hisp.dhis.scheduling.JobConfiguration; import java.util.Date; import java.util.HashSet; import java.util.Objects; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; /** * Class representing parameters for the analytics table generation process. * * @author Lars Helge Overland */ public class AnalyticsTableUpdateParams { /** * Number of last years for which to update tables. A zero value indicates * the "latest" data stored since last full analytics table generation. */ private Integer lastYears; /** * Indicates whether to skip update of resource tables. */ boolean skipResourceTables; /** * Analytics table types to skip. */ private Set<AnalyticsTableType> skipTableTypes = new HashSet<>(); /** * Job ID. */ private JobConfiguration jobId; /** * Start time for update process. */ private Date startTime; /** * Time of last successful analytics table update. */ private Date lastSuccessfulUpdate; private AnalyticsTableUpdateParams() { this.startTime = new Date(); } // Get methods public Integer getLastYears() { return lastYears; } public boolean isSkipResourceTables() { return skipResourceTables; } public Set<AnalyticsTableType> getSkipTableTypes() { return skipTableTypes; } public JobConfiguration getJobId() { return jobId; } public Date getStartTime() { return startTime; } public Date getLastSuccessfulUpdate() { return lastSuccessfulUpdate; } /** * Indicates whether this is a partial update of analytics tables, i.e. * if only certain partitions are to be updated and not all partitions * including the main analytics tables. */ public boolean isPartialUpdate() { return lastYears != null || isLatestUpdate(); } /** * Indicates whether this is an update of the "latest" partition. */ public boolean isLatestUpdate() { return Objects.equals( lastYears, AnalyticsTablePartition.LATEST_PARTITION ); } // toString @Override public String toString() { return MoreObjects.toStringHelper( this ) .add( "last years", lastYears ) .add( "skip resource tables", skipResourceTables ) .add( "skip table types", skipTableTypes ) .add( "start time", DateUtils.getLongDateString( startTime ) ) .toString(); } /** * Returns the from date based on the last years property, i.e. the first * day of year relative to the last years property. * * @return the from date based on the last years property. */ public Date getFromDate() { Date earliest = null; if ( lastYears != null ) { Calendar calendar = PeriodType.getCalendar(); DateTimeUnit dateTimeUnit = calendar.today(); dateTimeUnit = calendar.minusYears( dateTimeUnit, lastYears - 1 ); dateTimeUnit.setMonth( 1 ); dateTimeUnit.setDay( 1 ); earliest = dateTimeUnit.toJdkDate(); } return earliest; } // Builder of immutable instances /** * Returns a new instance of this parameter object. */ public AnalyticsTableUpdateParams instance() { AnalyticsTableUpdateParams params = new AnalyticsTableUpdateParams(); params.lastYears = this.lastYears; params.skipResourceTables = this.skipResourceTables; params.skipTableTypes = new HashSet<>( this.skipTableTypes ); params.jobId = this.jobId; params.startTime = this.startTime; params.lastSuccessfulUpdate = this.lastSuccessfulUpdate; return this; } public static Builder newBuilder() { return new AnalyticsTableUpdateParams.Builder(); } public static Builder newBuilder( AnalyticsTableUpdateParams analyticsTableUpdateParams ) { return new AnalyticsTableUpdateParams.Builder( analyticsTableUpdateParams ); } /** * Builder for {@link AnalyticsTableUpdateParams} instances. */ public static class Builder { private AnalyticsTableUpdateParams params; protected Builder() { this.params = new AnalyticsTableUpdateParams(); } protected Builder( AnalyticsTableUpdateParams analyticsTableUpdateParams ) { this.params = analyticsTableUpdateParams.instance(); } public Builder withLastYears( Integer lastYears ) { this.params.lastYears = lastYears; return this; } public Builder withLatestPartition() { this.params.lastYears = AnalyticsTablePartition.LATEST_PARTITION; return this; } public Builder withSkipResourceTables( boolean skipResourceTables ) { this.params.skipResourceTables = skipResourceTables; return this; } public Builder withSkipTableTypes( Set<AnalyticsTableType> skipTableTypes ) { this.params.skipTableTypes = skipTableTypes; return this; } public Builder withJobId( JobConfiguration jobId ) { this.params.jobId = jobId; return this; } public Builder withLastSuccessfulUpdate( Date lastSuccessfulUpdate ) { this.params.lastSuccessfulUpdate = lastSuccessfulUpdate; return this; } public Builder withStartTime( Date startTime ) { this.params.startTime = startTime; return this; } public AnalyticsTableUpdateParams build() { checkNotNull( this.params.startTime ); return this.params; } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1220"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package de.charite.compbio.exomiser.cli.options; import de.charite.compbio.exomiser.core.analysis.Settings.SettingsBuilder; import org.apache.commons.cli.OptionBuilder; /** * * @author Jules Jacobsen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7218071e17015c1813111d1001171c3201131c1517005c13115c0719">[email protected]</a>> */ public class PathogenicityFilterCutOffOptionMarshaller extends AbstractOptionMarshaller { public static final String KEEP_NON_PATHOGENIC_VARIANTS_OPTION = "keep-non-pathogenic"; public PathogenicityFilterCutOffOptionMarshaller() { option = OptionBuilder .hasOptionalArg() .withType(Boolean.class) .withArgName("true/false") .withDescription("Keep the predicted non-pathogenic variants that are normally removed by default. " + "These are defined as syonymous, intergenic, intronic, upstream, downstream or intronic ncRNA variants. " + "This setting can optionally take a true/false argument. Not including the argument is equivalent to specifying 'false'.") .withLongOpt(KEEP_NON_PATHOGENIC_VARIANTS_OPTION) .create("P"); } @Override public void applyValuesToSettingsBuilder(String[] values, SettingsBuilder settingsBuilder) { if (values == null) { //default is to remove the non-pathogenic variants, so this should be false settingsBuilder.removePathFilterCutOff(true); } else { //but the json/properties file specifies true or false, hence the optionArg settingsBuilder.removePathFilterCutOff(Boolean.parseBoolean(values[0])); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1221"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.github.avarabyeu.jashing.integration.vcs.github.model; import com.google.gson.annotations.SerializedName; import java.util.Date; /** * Repository model class */ public class Repository { private boolean fork; private boolean hasDownloads; private boolean hasIssues; private boolean hasWiki; @SerializedName("private") private boolean isPrivate; private Date createdAt; private Date pushedAt; private Date updatedAt; private int forks; private long id; @SerializedName("open_issues_count") private int openIssues; private int size; private int watchers; private Repository parent; private Repository source; private String cloneUrl; private String description; private String homepage; private String gitUrl; private String htmlUrl; private String language; private String defaultBranch; private String mirrorUrl; private String name; private String sshUrl; private String svnUrl; private String url; private User owner; /** * @return fork */ public boolean isFork() { return fork; } /** * @param fork Fork * @return this repository */ public Repository setFork(boolean fork) { this.fork = fork; return this; } /** * @return hasDownloads */ public boolean isHasDownloads() { return hasDownloads; } /** * @param hasDownloads Has Downloads * @return this repository */ public Repository setHasDownloads(boolean hasDownloads) { this.hasDownloads = hasDownloads; return this; } /** * @return hasIssues */ public boolean isHasIssues() { return hasIssues; } /** * @param hasIssues Has Issues * @return this repository */ public Repository setHasIssues(boolean hasIssues) { this.hasIssues = hasIssues; return this; } /** * @return hasWiki */ public boolean isHasWiki() { return hasWiki; } /** * @param hasWiki Has Wiki * @return this repository */ public Repository setHasWiki(boolean hasWiki) { this.hasWiki = hasWiki; return this; } /** * @return isPrivate */ public boolean isPrivate() { return isPrivate; } /** * @param isPrivate Is Private * @return this repository */ public Repository setPrivate(boolean isPrivate) { this.isPrivate = isPrivate; return this; } /** * @return createdAt */ public Date getCreatedAt() { return createdAt; } /** * @param createdAt Created At * @return this rdateepository */ public Repository setCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } /** * @return pushedAt */ public Date getPushedAt() { return pushedAt; } /** * @param pushedAt Pushed At * @return this repository */ public Repository setPushedAt(Date pushedAt) { this.pushedAt = pushedAt; return this; } /** * @return forks */ public int getForks() { return forks; } /** * @param forks Forks * @return this repository */ public Repository setForks(int forks) { this.forks = forks; return this; } /** * @return openIssues */ public int getOpenIssues() { return openIssues; } /** * @param openIssues Open Issues * @return this repository */ public Repository setOpenIssues(int openIssues) { this.openIssues = openIssues; return this; } /** * @return size */ public int getSize() { return size; } /** * @param size Size * @return this repository */ public Repository setSize(int size) { this.size = size; return this; } /** * @return watchers */ public int getWatchers() { return watchers; } /** * @param watchers Watchers * @return this repository */ public Repository setWatchers(int watchers) { this.watchers = watchers; return this; } /** * @return parent */ public Repository getParent() { return parent; } /** * @param parent Parent * @return this repository */ public Repository setParent(Repository parent) { this.parent = parent; return this; } /** * @return source */ public Repository getSource() { return source; } /** * @param source Source * @return this repository */ public Repository setSource(Repository source) { this.source = source; return this; } /** * @return cloneUrl */ public String getCloneUrl() { return cloneUrl; } /** * @param cloneUrl Clone URL * @return this repository */ public Repository setCloneUrl(String cloneUrl) { this.cloneUrl = cloneUrl; return this; } /** * @return description */ public String getDescription() { return description; } /** * @param description Description * @return this repository */ public Repository setDescription(String description) { this.description = description; return this; } /** * @return homepage */ public String getHomepage() { return homepage; } /** * @param homepage Homepage * @return this repository */ public Repository setHomepage(String homepage) { this.homepage = homepage; return this; } /** * @return gitUrl */ public String getGitUrl() { return gitUrl; } /** * @param gitUrl Get URL * @return this repository */ public Repository setGitUrl(String gitUrl) { this.gitUrl = gitUrl; return this; } /** * @return htmlUrl */ public String getHtmlUrl() { return htmlUrl; } /** * @param htmlUrl HTML URL * @return this repository */ public Repository setHtmlUrl(String htmlUrl) { this.htmlUrl = htmlUrl; return this; } /** * @return language */ public String getLanguage() { return language; } /** * @param language Language * @return this repository */ public Repository setLanguage(String language) { this.language = language; return this; } /** * @return defaultBranch */ public String getDefaultBranch() { return defaultBranch; } /** * @param defaultBranch Default Branch * @return this repository */ public Repository setDefaultBranch(String defaultBranch) { this.defaultBranch = defaultBranch; return this; } /** * @return masterBranch */ @Deprecated public String getMasterBranch() { return defaultBranch; } /** * @param masterBranch Master Branch * @return this repository */ @Deprecated public Repository setMasterBranch(String masterBranch) { this.defaultBranch = masterBranch; return this; } /** * @return mirrorUrl */ public String getMirrorUrl() { return mirrorUrl; } /** * @param mirrorUrl Mirror URL * @return this repository */ public Repository setMirrorUrl(String mirrorUrl) { this.mirrorUrl = mirrorUrl; return this; } /** * @return name */ public String getName() { return name; } /** * @param name Name * @return this repository */ public Repository setName(String name) { this.name = name; return this; } /** * @return sshUrl */ public String getSshUrl() { return sshUrl; } /** * @param sshUrl SSH URL * @return this repository */ public Repository setSshUrl(String sshUrl) { this.sshUrl = sshUrl; return this; } /** * @return svnUrl */ public String getSvnUrl() { return svnUrl; } /** * @param svnUrl SVN URL * @return this repository */ public Repository setSvnUrl(String svnUrl) { this.svnUrl = svnUrl; return this; } /** * @return url */ public String getUrl() { return url; } /** * @param url URL * @return this repository */ public Repository setUrl(String url) { this.url = url; return this; } /** * @return owner */ public User getOwner() { return owner; } /** * @param owner Owner * @return this repository */ public Repository setOwner(User owner) { this.owner = owner; return this; } /** * @return updatedAt */ public Date getUpdatedAt() { return updatedAt; } /** * @param updatedAt Updated At * @return this repository */ public Repository setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; return this; } /** * @return id */ public long getId() { return id; } /** * @param id ID * @return this repository */ public Repository setId(long id) { this.id = id; return this; } /** * Generate id for this repository * @return New generated ID */ public String generateId() { final User owner = this.owner; final String name = this.name; if (owner == null || name == null || name.length() == 0) return null; final String login = owner.getLogin(); if (login == null || login.length() == 0) return null; return login + "/" + name; //$NON-NLS-1$ } @Override public String toString() { return "Repository{" + "fork=" + fork + ", hasDownloads=" + hasDownloads + ", hasIssues=" + hasIssues + ", hasWiki=" + hasWiki + ", isPrivate=" + isPrivate + ", createdAt=" + createdAt + ", pushedAt=" + pushedAt + ", updatedAt=" + updatedAt + ", forks=" + forks + ", id=" + id + ", openIssues=" + openIssues + ", size=" + size + ", watchers=" + watchers + ", parent=" + parent + ", source=" + source + ", cloneUrl='" + cloneUrl + '\'' + ", description='" + description + '\'' + ", homepage='" + homepage + '\'' + ", gitUrl='" + gitUrl + '\'' + ", htmlUrl='" + htmlUrl + '\'' + ", language='" + language + '\'' + ", defaultBranch='" + defaultBranch + '\'' + ", mirrorUrl='" + mirrorUrl + '\'' + ", name='" + name + '\'' + ", sshUrl='" + sshUrl + '\'' + ", svnUrl='" + svnUrl + '\'' + ", url='" + url + '\'' + ", owner=" + owner + '}'; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1222"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * generated by Xtext */ package com.rockwellcollins.atc.agree.formatting; import org.eclipse.xtext.Keyword; import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter; import org.eclipse.xtext.formatting.impl.FormattingConfig; import org.eclipse.xtext.util.Pair; import com.google.inject.Inject; import com.rockwellcollins.atc.agree.services.AgreeGrammarAccess; public class AgreeFormatter extends AbstractDeclarativeFormatter { @Inject private AgreeGrammarAccess grammarAccess; @Override protected void configureFormatting(FormattingConfig c) { // It's usually a good idea to activate the following three statements. // They will add and preserve newlines around comments c.setLinewrap(0, 1, 2).before(grammarAccess.getSL_COMMENTRule()); // c.setLinewrap(0, 1, 2).before(grammarAccess.getML_COMMENTRule()); // c.setLinewrap(0, 1, 1).after(grammarAccess.getML_COMMENTRule()); c.setAutoLinewrap(120); // set line wrap after semicolon for (Keyword keywd : grammarAccess.findKeywords(";")) { c.setLinewrap().after(keywd); } // set no space before dots, commas and semicolons, right paren for (Keyword keywd : grammarAccess.findKeywords(".", ",", ";", ")")) { c.setNoSpace().before(keywd); } // set no space after dots and right paren for (Keyword keywd : grammarAccess.findKeywords(".", "(")) { c.setNoSpace().after(keywd); } // set and blank line between specification statements // But, it seems to not work for positioning with respect to // abstract base classes such as SpecStatement c.setLinewrap(2).after(grammarAccess.getSpecStatementRule()); c.setLinewrap(2).before(grammarAccess.getSynchStatementRule()); c.setLinewrap(2).before(grammarAccess.getOrderStatementRule()); c.setLinewrap(2).before(grammarAccess.getPropertyStatementRule()); c.setLinewrap(2).before(grammarAccess.getConstStatementRule()); c.setLinewrap(2).before(grammarAccess.getEnumStatementRule()); c.setLinewrap(2).before(grammarAccess.getEqStatementRule()); c.setLinewrap(2).before(grammarAccess.getAssignStatementRule()); c.setLinewrap(2).before(grammarAccess.getLinearizationDefExprRule()); c.setLinewrap(2).before(grammarAccess.getFnDefExprRule()); c.setLinewrap(2).before(grammarAccess.getLibraryFnDefExprRule()); c.setLinewrap(2).before(grammarAccess.getNodeDefExprRule()); c.setLinewrap(2).before(grammarAccess.getRecordDefExprRule()); c.setLinewrap(2).before(grammarAccess.getInputStatementRule()); // set line wrap before node def, let, tel, each local var c.setLinewrap().after(grammarAccess.getNodeStmtRule()); c.setLinewrap().after(grammarAccess.getNodeDefExprAccess().getArgsAssignment_3_1_1()); c.setLinewrap().after(grammarAccess.getNodeDefExprAccess().getReturnsKeyword_5()); c.setLinewrap().after(grammarAccess.getNodeBodyExprAccess().getLetKeyword_1()); c.setLinewrap().after(grammarAccess.getNodeBodyExprAccess().getTelKeyword_3()); c.setIndentationIncrement().after(grammarAccess.getNodeBodyExprAccess().getLetKeyword_1()); c.setIndentationDecrement().before(grammarAccess.getNodeBodyExprAccess().getTelKeyword_3()); // set line indentation inside for ITE c.setLinewrap().before(grammarAccess.getIfThenElseExprAccess().getThenKeyword_0_3()); //c.setIndentationIncrement().before(grammarAccess.getIfThenElseExprAccess().getBExprParserRuleCall_0_4_0()); //c.setIndentationDecrement().after(grammarAccess.getIfThenElseExprAccess().getBExprParserRuleCall_0_4_0()); c.setLinewrap().before(grammarAccess.getIfThenElseExprAccess().getElseKeyword_0_5()); //c.setIndentationIncrement().before(grammarAccess.getIfThenElseExprAccess().getCExprParserRuleCall_0_6_0()); //c.setIndentationDecrement().after(grammarAccess.getIfThenElseExprAccess().getCExprParserRuleCall_0_6_0()); // set line indentation inside all parentheses //grammarAccess.getRecordUpdateExprRule().g for (Pair<Keyword, Keyword> p : grammarAccess.findKeywordPairs("(", ")")) { c.setIndentationIncrement().after(p.getFirst()); c.setIndentationDecrement().before(p.getSecond()); } // set line indentation inside all curly brackets // set line wrap after each left curly bracket // set line wrap around each right curly bracket //grammarAccess.getRecordUpdateExprRule().g for (Pair<Keyword, Keyword> p : grammarAccess.findKeywordPairs("{", "}")) { c.setIndentationIncrement().after(p.getFirst()); c.setIndentationDecrement().before(p.getSecond()); c.setLinewrap().after(p.getFirst()); c.setLinewrap().around(p.getSecond()); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1223"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.spongepowered.forge.applaunch.loading.moddiscovery.locator; import cpw.mods.modlauncher.api.LamdbaExceptionUtils; import net.minecraftforge.fml.loading.LogMarkers; import net.minecraftforge.fml.loading.ModDirTransformerDiscoverer; import net.minecraftforge.fml.loading.StringUtils; import net.minecraftforge.fml.loading.moddiscovery.AbstractJarFileLocator; import net.minecraftforge.forgespi.locating.IModFile; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.common.applaunch.AppLaunch; import org.spongepowered.forge.applaunch.loading.moddiscovery.ModFileParsers; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public final class PluginsFolderLocator extends AbstractJarFileLocator { private static final Logger LOGGER = LogManager.getLogger(); @Override public List<IModFile> scanMods() { final List<Path> pluginDirectories = AppLaunch.pluginPlatform().pluginDirectories(); final List<IModFile> modFiles = new ArrayList<>(); for (final Path pluginDirectory : pluginDirectories) { PluginsFolderLocator.LOGGER.debug(LogMarkers.SCAN, "Scanning plugins directory '{}' for plugins", pluginDirectory); modFiles.addAll(this.scanForModsIn(pluginDirectory)); } return modFiles; } private List<IModFile> scanForModsIn(final Path pluginsDirectory) { final List<Path> excluded = ModDirTransformerDiscoverer.allExcluded(); return LamdbaExceptionUtils.uncheck(() -> Files.list(pluginsDirectory)) .filter((p) -> !excluded.contains(p)) .sorted(Comparator.comparing((path) -> StringUtils.toLowerCase(path.getFileName().toString()))) .filter((p) -> StringUtils.toLowerCase(p.getFileName().toString()).endsWith(".jar")) .map((p) -> ModFileParsers.newPluginInstance(p, this, "plugins")) .peek((f) -> this.modJars.compute(f, (mf, fs) -> this.createFileSystem(mf))) .filter(f -> { if (!f.identifyMods()) { final FileSystem fs = this.modJars.remove(f); if (fs != null) { LamdbaExceptionUtils.uncheck(fs::close); } return false; } return true; }) .collect(Collectors.toList()); } @Override public String name() { return "plugins directory"; } @Override public void initArguments(final Map<String, ?> arguments) { } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1224"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.eclipse.persistence.platform.server.wls; import java.lang.reflect.Method; import java.security.AccessController; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.internal.security.PrivilegedMethodInvoker; import org.eclipse.persistence.logging.SessionLog; import org.eclipse.persistence.platform.server.JMXEnabledPlatform; import org.eclipse.persistence.services.weblogic.MBeanWebLogicRuntimeServices; import org.eclipse.persistence.sessions.DatabaseSession; /** * PUBLIC: * * This is the concrete subclass responsible for representing WebLogic 10 specific behavior. * This includes WebLogic 10.3 behavior. */ public class WebLogic_10_Platform extends WebLogic_9_Platform implements JMXEnabledPlatform { // see http://docs.oracle.com/middleware/1213/wls/JMXCU/understandwls.htm#i1127767 /** This JNDI address is for JMX MBean registration */ private static final String JMX_JNDI_RUNTIME_REGISTER = "java:comp/env/jmx/runtime"; /** This JNDI address is for JMX MBean unregistration */ private static final String JMX_JNDI_RUNTIME_UNREGISTER = "java:comp/jmx/runtime"; /** This persistence.xml or sessions.xml property is used to override the moduleName */ protected static final String SERVER_SPECIFIC_MODULENAME_PROPERTY = "eclipselink.weblogic.moduleName"; /** This persistence.xml or sessions.xml property is used to override the applicationName */ protected static final String SERVER_SPECIFIC_APPLICATIONNAME_PROPERTY = "eclipselink.weblogic.applicationName"; /** * The following constants and attributes are used during reflective API calls */ /** Cache the WebLogic ThreadPoolRuntime for performance */ private ObjectName wlsThreadPoolRuntime = null; private static final String WLS_SERVICE_KEY = "com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean"; private static final String WLS_SERVER_RUNTIME = "ServerRuntime"; private static final String WLS_THREADPOOL_RUNTIME = "ThreadPoolRuntime"; private static final String WLS_EXECUTE_THREAD_GET_METHOD_NAME = "getExecuteThread"; private static final String WLS_APPLICATION_NAME_GET_METHOD_NAME = "getApplicationName"; private static final String WLS_MODULE_NAME_GET_METHOD_NAME = "getModuleName"; /** Search String in WebLogic ClassLoader for the application:persistence_unit name */ private static final String WLS_CLASSLOADER_APPLICATION_PU_SEARCH_STRING_PREFIX = "annotation: "; static { /** Override by subclass: Search String in application server ClassLoader for the application:persistence_unit name */ APP_SERVER_CLASSLOADER_APPLICATION_PU_SEARCH_STRING_PREFIX = "/deploy/"; /** Override by subclass: Search String in application server session for ejb modules */ APP_SERVER_CLASSLOADER_MODULE_EJB_SEARCH_STRING_PREFIX = ".jar/"; /** Override by subclass: Search String in application server session for war modules */ APP_SERVER_CLASSLOADER_MODULE_WAR_SEARCH_STRING_PREFIX = ".war/"; APP_SERVER_CLASSLOADER_APPLICATION_PU_SEARCH_STRING_POSTFIX = "postfix,match~not;required^"; APP_SERVER_CLASSLOADER_MODULE_EJB_WAR_SEARCH_STRING_POSTFIX = "postfix,match~not;required^"; } /** * INTERNAL: * Default Constructor: All behavior for the default constructor is inherited */ public WebLogic_10_Platform(DatabaseSession newDatabaseSession) { super(newDatabaseSession); this.enableRuntimeServices(); // Create the JMX MBean specific to this platform for later registration this.prepareServerSpecificServicesMBean(); } @Override public boolean isRuntimeServicesEnabledDefault() { return true; } /** * INTERNAL: * prepareServerSpecificServicesMBean(): Server specific implementation of the * creation and deployment of the JMX MBean to provide runtime services for the * databaseSession. * * Default is to do nothing. * Implementing platform classes must override this function and supply * the server specific MBean instance for later registration by calling it in the constructor. * * @return void * @see #isRuntimeServicesEnabled() * @see #disableRuntimeServices() * @see #registerMBean() */ public void prepareServerSpecificServicesMBean() { // No check for an existing cached MBean - we will replace it if it exists if(shouldRegisterRuntimeBean) { this.setRuntimeServicesMBean(new MBeanWebLogicRuntimeServices(getDatabaseSession())); } } /** * INTERNAL: * serverSpecificRegisterMBean(): Server specific implementation of the * creation and deployment of the JMX MBean to provide runtime services for my * databaseSession. * * @return void * @see #isRuntimeServicesEnabled() * @see #disableRuntimeServices() * @see #registerMBean() */ @Override public void serverSpecificRegisterMBean() { super.serverSpecificRegisterMBean(); // get and cache module and application name during registration initializeApplicationNameAndModuleName(); } /** * INTERNAL: * Return the MBeanServer to be used for MBean registration and deregistration.<br> * This MBeanServer reference is lazy loaded and cached on the platform.<br> * There are multiple ways of getting the MBeanServer<br> * <p> * 1) MBeanServerFactory static function - working for 3 of 4 servers WebSphere, JBoss and Glassfish in a generic way<br> * - JBoss returns 2 MBeanServers in the List - but one of them has a null domain - we don't use that one<br> * - WebLogic may return 2 MBeanServers - in that case we want to register with the one containing the "com.bea" tree * 2) ManagementFactory static function - what is the difference in using this one over the one returning a List of servers<br> * 3) JNDI lookup<br> * 4) Direct server specific native API<br></p> * We are using method (3)<br> * * @return the JMX specification MBeanServer */ @Override public MBeanServer getMBeanServer() { //super.getMBeanServer(); keep commented except for generic registration testing // 328006: This function overrides the generic version used for WebSphere, JBoss and Glassfish // Get a possible cached MBeanServer from the superclass first if(null == mBeanServer) { Context initialContext = null; try { initialContext = new InitialContext(); try { mBeanServer = (MBeanServer) initialContext.lookup(JMX_JNDI_RUNTIME_REGISTER); if (null == mBeanServer) { getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "failed_to_find_mbean_server", "null returned from JNDI lookup of " + JMX_JNDI_RUNTIME_REGISTER); } } catch (NamingException ne1) { //#440018 Fallback for the case when the JMX client classes are not located in a Java EE module mBeanServer = (MBeanServer) initialContext.lookup(JMX_JNDI_RUNTIME_UNREGISTER); if (null == mBeanServer) { getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "failed_to_find_mbean_server", "null returned from JNDI lookup of " + JMX_JNDI_RUNTIME_UNREGISTER); } } if (mBeanServer != null) { // Verify that this is a weblogic.management.jmx.mbeanserver.WLSMBeanServer if(mBeanServer.toString().indexOf("WLSMBeanServer") < 0) { // MBeanServer is not a WebLogic type - likely a com.sun.jmx.mbeanserver.JmxMBeanServer getAbstractSession().log(SessionLog.FINEST, SessionLog.SERVER, "sequencing_connected", null); } getAbstractSession().log(SessionLog.FINER, SessionLog.SERVER, "jmx_mbean_runtime_services_registration_mbeanserver_print", new Object[]{mBeanServer, mBeanServer.getMBeanCount(), mBeanServer.getDefaultDomain(), 0}); } } catch (NamingException ne) { getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "failed_to_find_mbean_server", ne); } catch (Exception exception) { getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "problem_registering_mbean", exception); } finally { // close the context // see http://e-docs.bea.com/wls/docs81/jndi/jndi.html#471919 // see http://e-docs.bea.com/wls/docs100/jndi/jndi.html#wp467275 try { if(null != initialContext) { initialContext.close(); } } catch (NamingException ne) { // exceptions on context close will be ignored, the context will be GC'd } } } return mBeanServer; } /** * INTERNAL: * Get the applicationName and moduleName from the runtime WebLogic MBean reflectively * @return * @deprecated */ protected void initializeApplicationNameAndModuleName() { // use non-reflective superclass method that searches the database session and classLoader strings // to be DEPRECATED // Get property from persistence.xml or sessions.xml String jpaModuleName = (String)getDatabaseSession().getProperty(SERVER_SPECIFIC_MODULENAME_PROPERTY); String jpaApplicationName = (String)getDatabaseSession().getProperty(SERVER_SPECIFIC_APPLICATIONNAME_PROPERTY); if (jpaModuleName != null) { setModuleName(jpaModuleName); } else { jpaModuleName = getModuleOrApplicationName(WLS_MODULE_NAME_GET_METHOD_NAME); // If we are running a version of WebLogic 10.3 that does not support ExecuteThreadRuntime (from 10.3+) then use the ClassLoader if(null != jpaModuleName && jpaModuleName.indexOf("@") != -1) { setModuleName(jpaModuleName.substring(jpaModuleName.indexOf("@") + 1)); } else { setModuleName(jpaModuleName); } } if (jpaApplicationName != null) { setApplicationName(jpaApplicationName); } else { jpaApplicationName = getModuleOrApplicationName(WLS_APPLICATION_NAME_GET_METHOD_NAME); // defer to the superclass implementation if(null == jpaApplicationName) { jpaApplicationName = super.getApplicationName(); } // If we are running a version of WebLogic 10.3 that does not support ExecuteThreadRuntime (from 10.3+) then use the ClassLoader if(null != jpaApplicationName && jpaApplicationName.indexOf("@") > -1) { setApplicationName(jpaApplicationName.substring(jpaApplicationName.indexOf("@") + 1)); } else { setApplicationName(jpaApplicationName); } } // TODO: remove: Final check for null values if(null == getApplicationName()) { setApplicationName(DEFAULT_SERVER_NAME_AND_VERSION); } if(null == getModuleName()) { setModuleName(DEFAULT_SERVER_NAME_AND_VERSION); } getAbstractSession().log(SessionLog.FINEST, SessionLog.SERVER, "mbean_get_application_name", getDatabaseSession().getName(), getApplicationName()); getAbstractSession().log(SessionLog.FINEST, SessionLog.SERVER, "mbean_get_module_name", getDatabaseSession().getName(), getModuleName()); } /** * INTERNAL: * This method will return the application|module name for WebLogic. * If the call to executeThread on the MBean fails - return the current classloader * Thread.currentThread().getContextClassLoader() * * ER 248746: Use reflection to obtain the application name (EJB, Web or MDB module) * Get either a String containing the module/applicationName or a WebLogic classLoader that contains the module/applicationName in the format... * weblogic.utils.classloaders.ChangeAwareClassLoader@19bb43f finder: weblogic.utils.classloaders.CodeGenClassFinder@ab7c2e annotation: org.eclipse.persistence.example.jpa.server.weblogic.enterpriseEAR@enterprise * If the getExecuteThread call failed, use the classloader string representation as backup. * If the classloader is not in the correct format, defer to superclass. * * @return String module|application Name from WLS */ private String getModuleOrApplicationName(String getMethodName) { Object classLoaderOrString = null;//this.getDatabaseSession().getPlatform().getConversionManager().getLoader(); Object executeThread = getExecuteThreadFromMBean(); if (executeThread != null) { try { // perform a reflective public java.lang.String // weblogic.work.ExecuteThreadRuntime.<getMethodName> Method getMethod = PrivilegedAccessHelper.getPublicMethod(executeThread.getClass(), getMethodName, new Class[] {}, false); if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) { classLoaderOrString = AccessController.doPrivileged(new PrivilegedMethodInvoker(getMethod, executeThread, (Object[]) null)); } else { classLoaderOrString = PrivilegedAccessHelper.invokeMethod(getMethod, executeThread); } if(classLoaderOrString instanceof ClassLoader) { // If we are running a version of WebLogic 10.3 that does not support ExecuteThreadRuntime (from 10.3+) then use the ClassLoader String jpaModuleNameRoot = ((ClassLoader)classLoaderOrString).toString(); if(null != jpaModuleNameRoot) { int startIndex = jpaModuleNameRoot.indexOf( WLS_CLASSLOADER_APPLICATION_PU_SEARCH_STRING_PREFIX); if(startIndex > -1) { classLoaderOrString = jpaModuleNameRoot.substring(startIndex + WLS_CLASSLOADER_APPLICATION_PU_SEARCH_STRING_PREFIX.length()); } } } } catch (Exception ex) { /* * If the reflective call to ExecuteThreadRuntime failed for * this an older version of WebLogic 10.3 failed, use the * classloader as a backup method */ getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "problem_with_reflective_weblogic_call_mbean", ex, getMethodName); } } return (String)classLoaderOrString; } /** * INTERNAL: * This convenience method will look up a WebLogic execute thread from the runtime * MBean tree. The execute thread contains application information. This code * will use the name of the current thread to lookup the corresponding ExecuteThread. * The ExecuteThread will allow us to obtain the application name (and version, etc). * * Note that the MBeanServer and ThreadPoolRuntime instances will be cached for * performance. * * @return application name or null if the name cannot be obtained */ private Object getExecuteThreadFromMBean() { // Initialize the threadPoolRuntime and get the executeThreadRuntime //this.getDatabaseSession().getPlatform().getConversionManager().getLoader(); if (getMBeanServer() != null) { // Lazy load the ThreadPoolRuntime instance if (wlsThreadPoolRuntime == null) { try { ObjectName service = new ObjectName(WLS_SERVICE_KEY); ObjectName serverRuntime = (ObjectName) getMBeanServer().getAttribute(service, WLS_SERVER_RUNTIME); wlsThreadPoolRuntime = (ObjectName) getMBeanServer().getAttribute(serverRuntime, WLS_THREADPOOL_RUNTIME); } catch (Exception ex) { getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "jmx_mbean_runtime_services_threadpool_initialize_failed", ex); } } // Get the executeThreadRuntimeObject if (wlsThreadPoolRuntime != null) { try { // Perform a reflective getExecuteThread() return getMBeanServer().invoke(wlsThreadPoolRuntime, WLS_EXECUTE_THREAD_GET_METHOD_NAME, new Object[] { Thread.currentThread().getName() }, new String[] { String.class.getName() }); } catch (Exception ex) { /* * If the reflective call to get the executeThreadRuntime object failed on the MBean because * this an older version of WebLogic 10.3, continue and use the classloader as a backup method */ getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "jmx_mbean_runtime_services_get_executethreadruntime_object_failed", ex); } } } return null; } /** * Return the method for the WebLogic JDBC connection wrapper vendorConnection. * WLS 10.3.4.0 added a getVendorConnectionSafe that does not invalidate the connection, * so use this if available. */ protected Method getVendorConnectionMethod() { if ((this.vendorConnectionMethod == null) && (!getWebLogicConnectionClass().equals(void.class))) { try { this.vendorConnectionMethod = PrivilegedAccessHelper.getDeclaredMethod(getWebLogicConnectionClass(), "getVendorConnectionSafe", new Class[0]); } catch (NoSuchMethodException not1034) { try { this.vendorConnectionMethod = PrivilegedAccessHelper.getDeclaredMethod(getWebLogicConnectionClass(), "getVendorConnection", new Class[0]); } catch (NoSuchMethodException exception) { getDatabaseSession().getSessionLog().logThrowable(SessionLog.WARNING, SessionLog.SERVER, exception); } } } return this.vendorConnectionMethod; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1225"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.jtalks.jcommune.web.controller; import org.jtalks.jcommune.model.entity.JCUser; import org.jtalks.jcommune.model.entity.Language; import org.jtalks.jcommune.model.entity.Post; import org.jtalks.jcommune.service.PostService; import org.jtalks.jcommune.service.UserService; import org.jtalks.jcommune.service.exceptions.NotFoundException; import org.jtalks.jcommune.service.nontransactional.ImageConverter; import org.jtalks.jcommune.web.dto.EditUserProfileDto; import org.jtalks.jcommune.web.dto.json.JsonResponse; import org.jtalks.jcommune.web.dto.json.JsonResponseStatus; import org.jtalks.jcommune.web.util.BreadcrumbBuilder; import org.jtalks.jcommune.web.validation.editors.DefaultStringEditor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.support.RequestContextUtils; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.util.Locale; /** * Controller for User related actions: registration, user profile operations and so on. * * @author Kirill Afonin * @author Alexandre Teterin * @author Max Malakhov * @author Eugeny Batov * @author Evgeniy Naumenko * @author Anuar_Nurmakanov */ @Controller public class UserProfileController { public static final String EDIT_PROFILE = "editProfile"; public static final String EDITED_USER = "editedUser"; public static final String BREADCRUMB_LIST = "breadcrumbList"; private UserService userService; private BreadcrumbBuilder breadcrumbBuilder; private ImageConverter imageConverter; private PostService postService; /** * This method turns the trim binder on. Trim binder * removes leading and trailing spaces from the submitted fields. * So, it ensures, that all validations will be applied to * trimmed field values only. * <p/> There is no need for trim edit password fields, * so they are processed with {@link DefaultStringEditor} * @param binder Binder object to be injected */ @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(String.class, "newUserPassword", new DefaultStringEditor(true)); binder.registerCustomEditor(String.class, "newUserPasswordConfirm", new DefaultStringEditor(true)); binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); } /** * @param userService to get current user and user by id * @param breadcrumbBuilder the object which provides actions on {@link BreadcrumbBuilder} entity * @param imageConverter to prepare user avatar for view * @param postService to get all user's posts */ @Autowired public UserProfileController(UserService userService, BreadcrumbBuilder breadcrumbBuilder, @Qualifier("avatarPreprocessor") ImageConverter imageConverter, PostService postService) { this.userService = userService; this.breadcrumbBuilder = breadcrumbBuilder; this.imageConverter = imageConverter; this.postService = postService; } /** * Show user profile page with user info. * * @param id user identifier * @return user details view with {@link JCUser} object. * @throws NotFoundException if user with given id not found. */ @RequestMapping(value = "/users/{id}", method = RequestMethod.GET) public ModelAndView showProfilePage(@PathVariable Long id) throws NotFoundException { JCUser user = userService.get(id); return getUserProfileModelAndView(user); } /** * This method is a shortcut for user profile access. It may be usefull when we haven't got * the specific id, but simply want to access current user's profile. * <p/> * Requires user to be authorized. * * @return user details view with {@link JCUser} object. */ @RequestMapping(value = "/user", method = RequestMethod.GET) public ModelAndView showCurrentUserProfilePage() { JCUser user = userService.getCurrentUser(); return getUserProfileModelAndView(user); } /** * Formats model and view for representing user's details * * @param user user * @return user's details */ private ModelAndView getUserProfileModelAndView(JCUser user){ return new ModelAndView("userDetails") .addObject("user", user) // bind separately to get localized value .addObject("language", user.getLanguage()); } /** * Show edit user profile page for current logged in user. * * @return edit user profile page * @throws NotFoundException throws if current logged in user was not found */ @RequestMapping(value = "/users/edit/{editedUserId}", method = RequestMethod.GET) public ModelAndView startEditUserProfile(@PathVariable Long editedUserId) throws NotFoundException { checkPermissionsToEditProfile(editedUserId); JCUser editedUser = userService.get(editedUserId); EditUserProfileDto editedUserDto = convertUserForView(editedUser); ModelAndView mav = new ModelAndView(EDIT_PROFILE, EDITED_USER, editedUserDto); mav.addObject("contacts", editedUser.getUserContacts()); return mav; } /** * Converts passed user to data transfer object for view. * * @param user passed user * @return data transfer object for view */ private EditUserProfileDto convertUserForView(JCUser user) { EditUserProfileDto editUserProfileDto = new EditUserProfileDto(user); byte[] avatar = user.getAvatar(); editUserProfileDto.setAvatar(imageConverter.prepareHtmlImgSrc(avatar)); return editUserProfileDto; } /** * Update user profile info. Check if the user enter valid data and update profile in database. * In error case return into the edit profile page and draw the error. * <p/> * * @param editedProfileDto dto populated by user * @param result binding result which contains the validation result * @param response http servlet response * @return in case of errors return back to edit profile page, in another case return to user details page * @throws NotFoundException if edited user doesn't exist in system */ private void checkPermissionsToEditProfile(long editedUserId) { JCUser editorUser = userService.getCurrentUser(); if (editorUser.getId() == editedUserId) { userService.checkPermissionToEditOwnProfile(editorUser.getId()); } else { userService.checkPermissionToEditOtherProfiles(editorUser.getId()); } } /** * Show page with post of user. * SpEL pattern in a var name indicates we want to consume all the symbols in a var, * even dots, which Spring MVC uses as file extension delimiters by default. * * @param page number current page * @param id database user identifier * @return post list of user * @throws NotFoundException if user with given id not found. */ @RequestMapping(value = "/users/{id}/postList", method = RequestMethod.GET) public ModelAndView showUserPostList(@PathVariable Long id, @RequestParam(value = "page", defaultValue = "1", required = false) String page) throws NotFoundException { JCUser user = userService.get(id); Page<Post> postsPage = postService.getPostsOfUser(user, page); return new ModelAndView("userPostList") .addObject("user", user) .addObject("postsPage", postsPage) .addObject(BREADCRUMB_LIST, breadcrumbBuilder.getForumBreadcrumb()); } @RequestMapping(value = "**/language", method = RequestMethod.GET) public JsonResponse saveUserLanguage(/*@PathVariable("lang") String lang,*/ @RequestParam(value = "lang") String lang, HttpServletResponse response, HttpServletRequest request) throws ServletException { JCUser jcuser = userService.getCurrentUser(); if(!jcuser.isAnonymous()){ Language languageFromRequest = Language.byLocale(new Locale(lang)); try{ jcuser.setLanguage(languageFromRequest); userService.saveEditedUserProfile(jcuser.getId(), new EditUserProfileDto(jcuser).getUserInfoContainer()); }catch (Exception e){ throw new ServletException("Language save failed."); } } LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); localeResolver.setLocale(request, response, jcuser.getLanguage().getLocale()); // return "redirect:" + request.getHeader("Referer"); return new JsonResponse(JsonResponseStatus.SUCCESS, null); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1226"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.atlassian.jira.plugins.dvcs.spi.github.webwork; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.atlassian.jira.plugins.dvcs.exception.SourceControlException; import com.atlassian.jira.plugins.dvcs.exception.SourceControlException.InvalidResponseException; import com.atlassian.jira.plugins.dvcs.util.CustomStringUtils; public class GithubOAuthUtils { private final Logger log = LoggerFactory.getLogger(GithubOAuthUtils.class); private final String baseUrl; private final String clientId; private final String secret; public GithubOAuthUtils(String baseUrl, String clientId, String secret) { this.baseUrl = baseUrl; this.clientId = clientId; this.secret = secret; } public String createGithubRedirectUrl(String nextAction, String url, String xsrfToken, String organization, String autoLinking, String autoSmartCommits) { String encodedRepositoryUrl = encode(url); // Redirect back URL String redirectBackUrl = baseUrl + "/secure/admin/" + nextAction + ".jspa?url=" + encodedRepositoryUrl + "&atl_token=" + xsrfToken + "&organization=" + organization + "&autoLinking=" + autoLinking + "&autoSmartCommits=" + autoSmartCommits; String encodedRedirectBackUrl = encode(redirectBackUrl); // build URL to github String githubAuthorizeUrl = url + "/login/oauth/authorize?scope=repo&client_id=" + clientId + "&redirect_uri=" + encodedRedirectBackUrl; return githubAuthorizeUrl; } public String requestAccessToken(String githubHostUrl, String code) { log.debug("Requesting access token at " + githubHostUrl + " with code " + code); URL url; HttpURLConnection conn; BufferedReader rd; String line; String result = ""; if (StringUtils.isEmpty(code)) { throw new SourceControlException("Ops, no access code returned. Did you click Allow?"); } String githubUrl = githubUrl(githubHostUrl); try { String requestUrl = githubUrl + "/login/oauth/access_token"; String urlParameters = "client_id=" + clientId + "&client_secret=" + secret + "&code=" + code; log.debug("requestAccessToken() - " + requestUrl + " with parameters " + urlParameters); url = new URL(requestUrl); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setInstanceFollowRedirects(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); conn.setUseCaches (false); DataOutputStream wr = new DataOutputStream(conn.getOutputStream ()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { log.debug("RESPONSE: " + line); result += line; } rd.close(); } catch (MalformedURLException e) { throw new SourceControlException("Error obtaining access token.",e); } catch (IOException ioe) { throw new SourceControlException("Error obtaining access token. Cannot access " + githubUrl + " from Jira.",ioe); } catch (Exception e) { throw new SourceControlException("Error obtaining access token. Please check your credentials.",e); } if (result.startsWith("error=")) { String errorCode = result.replaceAll("error=", ""); String error = errorCode; if (errorCode.equals("incorrect_client_credentials")) { error = "Incorrect client credentials"; } else if (errorCode.equals("bad_verification_code")) { error = "Bad verification code"; } throw new SourceControlException("Error obtaining access token: " + error); } else if (!result.startsWith("access_token")) { log.error("Requested access token response is invalid"); throw new InvalidResponseException("Error obtaining access token. Response is invalid."); } return result.replaceAll("access_token=([^&]*).*", "$1"); } private String githubUrl(String githubHostUrl) { return StringUtils.isNotBlank(githubHostUrl) ? githubHostUrl : "https://github.com"; } public String requestAccessToken(String code) { return requestAccessToken(null, code); } public static String encode(String url) { return CustomStringUtils.encode(url); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1227"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.languagetool.rules.fr; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.languagetool.AnalyzedToken; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.language.French; import org.languagetool.rules.*; import org.languagetool.rules.patterns.RuleFilter; import org.languagetool.synthesis.FrenchSynthesizer; public class PostponedAdjectiveConcordanceFilter extends RuleFilter { /** * Patterns */ private final int maxLevels = 4; private static final Pattern NOM = Pattern.compile("[NZ] .*"); private static final Pattern NOM_MS = Pattern.compile("[NZ] m s"); private static final Pattern NOM_FS = Pattern.compile("[NZ] f s"); private static final Pattern NOM_MP = Pattern.compile("[NZ] m p"); private static final Pattern NOM_MN = Pattern.compile("[NZ] m sp"); private static final Pattern NOM_FP = Pattern.compile("[NZ] f p"); private static final Pattern NOM_CS = Pattern.compile("[NZ] e s"); private static final Pattern NOM_CP = Pattern.compile("[NZ] e sp"); private static final Pattern NOM_DET = Pattern.compile("[NZ] .*|(P\\+)?D .*"); private static final Pattern _GN_ = Pattern.compile("_GN_.*"); private static final Pattern _GN_MS = Pattern.compile("_GN_MS"); private static final Pattern _GN_FS = Pattern.compile("_GN_FS"); private static final Pattern _GN_MP = Pattern.compile("_GN_MP"); private static final Pattern _GN_FP = Pattern.compile("_GN_FP"); private static final Pattern _GN_CS = Pattern.compile("_GN_[MF]S"); private static final Pattern _GN_CP = Pattern.compile("_GN_[MF]P"); private static final Pattern _GN_MN = Pattern.compile("_GN_M[SP]"); private static final Pattern _GN_FN = Pattern.compile("_GN_F[SP]"); private static final Pattern DET = Pattern.compile("(P\\+)?D .*"); private static final Pattern DET_CS = Pattern.compile("(P\\+)?D e s"); private static final Pattern DET_MS = Pattern.compile("(P\\+)?D m s"); private static final Pattern DET_FS = Pattern.compile("(P\\+)?D f s"); private static final Pattern DET_MP = Pattern.compile("(P\\+)?D m p"); private static final Pattern DET_FP = Pattern.compile("(P\\+)?D f p"); private static final Pattern DET_CP = Pattern.compile("(P\\+)?D e p"); // NEW for French!! private static final Pattern GN_MS = Pattern.compile("[NZ] [me] (s|sp)|J [me] (s|sp)|V ppa m s|(P\\+)?D m (s|sp)"); private static final Pattern GN_FS = Pattern.compile("[NZ] [fe] (s|sp)|J [fe] (s|sp)|V ppa f s|(P\\+)?D f (s|sp)"); private static final Pattern GN_MP = Pattern.compile("[NZ] [me] (p|sp)|J [me] (p|sp)|V ppa m p|(P\\+)?D m (p|sp)"); private static final Pattern GN_FP = Pattern.compile("[NZ] [fe] (p|sp)|J [fe] (p|sp)|V ppa f p|(P\\+)?D f (p|sp)"); private static final Pattern GN_CP = Pattern.compile("[NZ] [fme] (p|sp)|J [fme] (p|sp)|(P\\+)?D [fme] (p|sp)"); private static final Pattern GN_CS = Pattern.compile("[NZ] [fme] (s|sp)|J [fme] (s|sp)|(P\\+)?D [fme] (s|sp)"); private static final Pattern GN_MN = Pattern.compile("[NZ] [me] (s|p|sp)|J [me] (s|p|sp)|(P\\+)?D [me] (s|p|sp)"); // NEW for French!! private static final Pattern GN_FN = Pattern.compile("[NZ] [fe] (s|p|sp)|J [fe] (s|p|sp)|(P\\+)?D [fe] (s|p|sp)"); // NEW for French!! //private static final Pattern NOM_ADJ = Pattern.compile("[NZ] *|J .*|V ppa .*"); private static final Pattern ADJECTIU = Pattern.compile("J .*|V ppa .*|PX.*"); private static final Pattern ADJECTIU_MS = Pattern.compile("J [me] (s|sp)|V ppa m s"); private static final Pattern ADJECTIU_FS = Pattern.compile("J [fe] (s|sp)|V ppa f s"); private static final Pattern ADJECTIU_MP = Pattern.compile("J [me] (p|sp)|V ppa m p"); private static final Pattern ADJECTIU_FP = Pattern.compile("J [fe] (p|sp)|V ppa f p"); private static final Pattern ADJECTIU_CP = Pattern.compile("J e (p|sp)"); private static final Pattern ADJECTIU_CS = Pattern.compile("J e (s|sp)"); private static final Pattern ADJECTIU_MN = Pattern.compile("J m sp"); // NEW for French!! private static final Pattern ADJECTIU_FN = Pattern.compile("J f sp"); // NEW for French!! private static final Pattern ADJECTIU_S = Pattern.compile("J .* (s|sp)|V ppa . s"); private static final Pattern ADJECTIU_P = Pattern.compile("J .* (p|sp)|V ppa . p"); private static final Pattern ADJECTIU_M = Pattern.compile("J [me] .*|V ppa [me] .*"); // NEW for French!! private static final Pattern ADJECTIU_F = Pattern.compile("J [fe] .*|V ppa [fe] .*"); // NEW for French!! private static final Pattern ADVERBI = Pattern.compile("A"); private static final Pattern CONJUNCIO = Pattern.compile("C .*"); private static final Pattern PUNTUACIO = Pattern.compile("_PUNCT"); private static final Pattern LOC_ADV = Pattern.compile("A"); private static final Pattern ADVERBIS_ACCEPTATS = Pattern.compile("A"); private static final Pattern COORDINACIO_IONI = Pattern.compile("et|ou|ni"); private static final Pattern KEEP_COUNT = Pattern.compile("Y|J .*|N .*|D .*|P.*|V ppa .*|M nonfin|UNKNOWN|Z.*|V.* inf|V ppr"); private static final Pattern KEEP_COUNT2 = Pattern.compile(",|et|ou|ni"); private static final Pattern STOP_COUNT = Pattern.compile("[;:\\(\\)\\[\\]–—―‒]"); private static final Pattern PREPOSICIONS = Pattern.compile("P"); private static final Pattern PREPOSICIO_CANVI_NIVELL = Pattern.compile("d'|de|des|du|à|au|aux|en|dans|sur|entre|par|pour|avec|sans|contre|comme"); private static final Pattern VERB = Pattern.compile("V.* (inf|ind|sub|con|ppr|imp).*"); // Any verb that is not V ppa private static final Pattern INFINITIVE = Pattern.compile("V.* inf"); private static final Pattern GV = Pattern.compile("_GV_"); private static final FrenchSynthesizer synth = new FrenchSynthesizer(new French()); boolean adverbAppeared = false; boolean conjunctionAppeared = false; boolean punctuationAppeared = false; boolean infinitiveAppeared = false; @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens) throws IOException { // int i = 0; AnalyzedTokenReadings[] tokens = match.getSentence().getTokensWithoutWhitespace(); int i = patternTokenPos; int j; boolean isPlural = true; boolean isPrevNoun = false; Pattern substPattern = null; Pattern gnPattern = null; Pattern adjPattern = null; boolean canBeMS = false; boolean canBeFS = false; boolean canBeMP = false; boolean canBeFP = false; boolean canBeP = false; /* Count all nouns and determiners before the adjectives */ // Takes care of acceptable combinations. int[] cNt = new int[maxLevels]; int[] cNMS = new int[maxLevels]; int[] cNFS = new int[maxLevels]; int[] cNMP = new int[maxLevels]; int[] cNMN = new int[maxLevels]; int[] cNFP = new int[maxLevels]; int[] cNCS = new int[maxLevels]; int[] cNCP = new int[maxLevels]; int[] cDMS = new int[maxLevels]; int[] cDFS = new int[maxLevels]; int[] cDMP = new int[maxLevels]; int[] cDFP = new int[maxLevels]; int[] cN = new int[maxLevels]; int[] cD = new int[maxLevels]; int level = 0; j = 1; initializeApparitions(); while (i - j > 0 && keepCounting(tokens[i - j]) && level < maxLevels) { if (!isPrevNoun) { if (matchPostagRegexp(tokens[i - j], NOM) || ( i - j - 1 > 0 && !matchPostagRegexp(tokens[i - j], NOM) && matchPostagRegexp(tokens[i - j], ADJECTIU) && matchPostagRegexp(tokens[i - j - 1], DET))) { if (matchPostagRegexp(tokens[i - j], _GN_MS)) { cNMS[level]++; canBeMS = true; } if (matchPostagRegexp(tokens[i - j], _GN_FS)) { cNFS[level]++; canBeFS = true; } if (matchPostagRegexp(tokens[i - j], _GN_MP)) { cNMP[level]++; canBeMP = true; } if (matchPostagRegexp(tokens[i - j], _GN_FP)) { cNFP[level]++; canBeFP = true; } } if (!matchPostagRegexp(tokens[i - j], _GN_)) { if (matchPostagRegexp(tokens[i - j], NOM_MS)) { cNMS[level]++; canBeMS = true; } else if (matchPostagRegexp(tokens[i - j], NOM_FS)) { cNFS[level]++; canBeFS = true; } else if (matchPostagRegexp(tokens[i - j], NOM_MP)) { cNMP[level]++; canBeMP = true; } else if (matchPostagRegexp(tokens[i - j], NOM_MN)) { cNMN[level]++; canBeMS = true; canBeMP = true; } else if (matchPostagRegexp(tokens[i - j], NOM_FP)) { cNFP[level]++; canBeFP = true; } else if (matchPostagRegexp(tokens[i - j], NOM_CS)) { cNCS[level]++; canBeMS = true; canBeFS = true; } else if (matchPostagRegexp(tokens[i - j], NOM_CP)) { cNCP[level]++; canBeFP = true; canBeMP = true; } } } // avoid two consecutive nouns if (matchPostagRegexp(tokens[i - j], NOM)) { cNt[level]++; isPrevNoun = true; // initializeApparitions(); } else { isPrevNoun = false; } if (matchPostagRegexp(tokens[i - j], DET_CS)) { if (matchPostagRegexp(tokens[i - j + 1], NOM_MS)) { cDMS[level]++; canBeMS = true; } if (matchPostagRegexp(tokens[i - j + 1], NOM_FS)) { cDFS[level]++; canBeFS = true; } } if (matchPostagRegexp(tokens[i - j], DET_CP)) { if (matchPostagRegexp(tokens[i - j + 1], NOM_MP)) { cDMS[level]++; canBeMP = true; } if (matchPostagRegexp(tokens[i - j + 1], NOM_FP)) { cDFS[level]++; canBeFP = true; } } //TODO DET_CS, DET_CP without noun afterwards if (!matchPostagRegexp(tokens[i - j], ADVERBI)) { if (matchPostagRegexp(tokens[i - j], DET_MS)) { cDMS[level]++; canBeMS = true; } if (matchPostagRegexp(tokens[i - j], DET_FS)) { cDFS[level]++; canBeFS = true; } if (matchPostagRegexp(tokens[i - j], DET_MP)) { cDMP[level]++; canBeMP = true; } if (matchPostagRegexp(tokens[i - j], DET_FP)) { cDFP[level]++; canBeFP = true; } } if (i - j - 1 > 0) { if (matchRegexp(tokens[i - j].getToken(), PREPOSICIO_CANVI_NIVELL) && !matchPostagRegexp(tokens[i - j], CONJUNCIO) && !matchRegexp(tokens[i - j - 1].getToken(), COORDINACIO_IONI) && !matchPostagRegexp(tokens[i - j + 1], ADVERBI)) { level++; } } j = updateJValue(tokens, i, j, level); updateApparitions(tokens[i - j]); j++; } level++; if (level > maxLevels) { level = maxLevels; } j = 0; int cNtotal = 0; int cDtotal = 0; while (j < level) { cN[j] = cNMS[j] + cNFS[j] + cNMP[j] + cNFP[j] + cNCS[j] + cNCP[j] + cNMN[j]; cD[j] = cDMS[j] + cDFS[j] + cDMP[j] + cDFP[j]; cNtotal += cN[j]; cDtotal += cD[j]; // exceptions: adjective is plural and there are several nouns before if (matchPostagRegexp(tokens[i], ADJECTIU_MP) && (cN[j] > 1 || cD[j] > 1) && (cNMS[j] + cNMN[j] + cNMP[j] + cNCS[j] + cNCP[j] + cDMS[j] + cDMP[j]) > 0 && (cNFS[j] + cNFP[j] <= cNt[j])) { return null; } if (matchPostagRegexp(tokens[i], ADJECTIU_FP) && (cN[j] > 1 || cD[j] > 1) && ((cNMS[j] + cNMP[j] + cNMN[j] + cDMS[j] + cDMP[j]) == 0 || (cNt[j] > 0 && cNFS[j] + cNFP[j] >= cNt[j]))) { return null; } // Adjective can't be singular if (cN[j] + cD[j] > 0) { // && level>1 isPlural = isPlural && cD[j] > 1 && level>1; // cN[j]>1 canBeP = canBeP || cN[j]>1; } j++; } // there is no noun, (no determinant --> && cDtotal==0) if (cNtotal == 0 && cDtotal == 0) { return null; } // patterns according to the analyzed adjective if (matchPostagRegexp(tokens[i], ADJECTIU_CS)) { substPattern = GN_CS; adjPattern = ADJECTIU_S; gnPattern = _GN_CS; } else if (matchPostagRegexp(tokens[i], ADJECTIU_CP)) { substPattern = GN_CP; adjPattern = ADJECTIU_P; gnPattern = _GN_CP; } else if (matchPostagRegexp(tokens[i], ADJECTIU_MN)) { substPattern = GN_MN; adjPattern = ADJECTIU_M; gnPattern = _GN_MN; } else if (matchPostagRegexp(tokens[i], ADJECTIU_FN)) { substPattern = GN_FN; adjPattern = ADJECTIU_FN; gnPattern = _GN_FN; } else if (matchPostagRegexp(tokens[i], ADJECTIU_MS)) { substPattern = GN_MS; adjPattern = ADJECTIU_MS; gnPattern = _GN_MS; } else if (matchPostagRegexp(tokens[i], ADJECTIU_FS)) { substPattern = GN_FS; adjPattern = ADJECTIU_FS; gnPattern = _GN_FS; } else if (matchPostagRegexp(tokens[i], ADJECTIU_MP)) { substPattern = GN_MP; adjPattern = ADJECTIU_MP; gnPattern = _GN_MP; } else if (matchPostagRegexp(tokens[i], ADJECTIU_FP)) { substPattern = GN_FP; adjPattern = ADJECTIU_FP; gnPattern = _GN_FP; } if (substPattern == null || gnPattern == null || adjPattern == null) { return null; } // combinations Det/Nom + adv (1,2..) + adj. // If there is agreement, the rule doesn't match j = 1; boolean keepCount = true; while (i - j > 0 && keepCount) { if (matchPostagRegexp(tokens[i - j], NOM_DET) && matchPostagRegexp(tokens[i - j], gnPattern)) { return null; // there is a previous agreeing noun } else if (!matchPostagRegexp(tokens[i - j], _GN_) && matchPostagRegexp(tokens[i - j], substPattern)) { return null; // there is a previous agreeing noun } keepCount = !matchPostagRegexp(tokens[i - j], NOM_DET); j++; } // Necessary condition: previous token is a non-agreeing noun // or it is adjective or adverb (not preceded by verb) // /*&& !matchPostagRegexp(tokens[i],NOM)*/ if ( (matchPostagRegexp(tokens[i - 1], NOM) && !matchPostagRegexp(tokens[i - 1], substPattern)) || (matchPostagRegexp(tokens[i - 1], _GN_) && !matchPostagRegexp(tokens[i - 1], gnPattern)) || (matchPostagRegexp(tokens[i - 1], ADJECTIU) && !matchPostagRegexp(tokens[i - 1], adjPattern)) || (i > 2 && matchPostagRegexp(tokens[i - 1], ADVERBIS_ACCEPTATS) && !matchPostagRegexp(tokens[i - 2], VERB) && !matchPostagRegexp(tokens[i - 2], PREPOSICIONS)) || (i > 3 && matchPostagRegexp(tokens[i - 1], LOC_ADV) && matchPostagRegexp(tokens[i - 2], LOC_ADV) && !matchPostagRegexp(tokens[i - 3], VERB) && !matchPostagRegexp(tokens[i - 3], PREPOSICIONS))) { } else { return null; } // Adjective can't be singular. The rule matches if (!(isPlural && matchPostagRegexp(tokens[i], ADJECTIU_S))) { // look into previous words j = 1; initializeApparitions(); while (i - j > 0 && keepCounting(tokens[i - j]) && (level > 1 || j < 4)) { // there is a previous agreeing noun if (!matchPostagRegexp(tokens[i - j], _GN_) && matchPostagRegexp(tokens[i - j], NOM_DET) && matchPostagRegexp(tokens[i - j], substPattern)) { return null; // there is a previous agreeing adjective (in a nominal group) } else if (matchPostagRegexp(tokens[i - j], gnPattern)) { return null; // if there is no nominal group, it requires noun } /* * else if (!matchPostagRegexp(tokens[i - j], _GN_) && * matchPostagRegexp(tokens[i - j], substPattern)) { return null; // there is a * previous agreeing noun } */ j = updateJValue(tokens, i, j, 0); updateApparitions(tokens[i - j]); j++; } } // The rule matches // Synthesize suggestions List<String> suggestions = new ArrayList<>(); AnalyzedToken at = getAnalyzedToken(tokens[patternTokenPos], ADJECTIU_CS); if (at != null) { suggestions.addAll(Arrays.asList(synth.synthesize(at,"J e p", true))); } if (suggestions.isEmpty()) { at = getAnalyzedToken(tokens[patternTokenPos], ADJECTIU_CP); if (at != null) { suggestions.addAll(Arrays.asList(synth.synthesize(at,"J e s", true))); } } if (suggestions.isEmpty() && isPlural) { at = getAnalyzedToken(tokens[patternTokenPos], ADJECTIU_P); if (at != null) { suggestions.addAll(Arrays.asList(synth.synthesize(at, "J . p|V ppa . p", true))); } } at = getAnalyzedToken(tokens[patternTokenPos], ADJECTIU); if (at != null && suggestions.isEmpty()) { if (canBeMS && !isPlural) { suggestions.addAll(Arrays.asList(synth.synthesize(at, "J m s|V ppa m s", true))); } if (canBeFS && !isPlural) { suggestions.addAll(Arrays.asList(synth.synthesize(at, "J f s|V ppa f s", true))); } if (canBeMP) { suggestions.addAll(Arrays.asList(synth.synthesize(at, "J m p|V ppa m p", true))); } if (canBeFP) { suggestions.addAll(Arrays.asList(synth.synthesize(at, "J f p|V ppa f p", true))); } if (canBeMS && (isPlural || canBeP)) { suggestions.addAll(Arrays.asList(synth.synthesize(at, "J m p|V ppa m p", true))); } if (canBeFS && !canBeMS && (isPlural || canBeP)) { suggestions.addAll(Arrays.asList(synth.synthesize(at, "J f p|V ppa f p", true))); } } //set suggestion removing duplicates suggestions = suggestions.stream().distinct().collect(Collectors.toList()); // avoid the original token as suggestion if (suggestions.contains(tokens[patternTokenPos].getToken().toLowerCase())) { suggestions.remove(tokens[patternTokenPos].getToken().toLowerCase()); } match.setSuggestedReplacements(suggestions); return match; } private int updateJValue(AnalyzedTokenReadings[] tokens, int i, int j, int level) { /* if (level > 0 && matchRegexp(tokens[i - j].getToken(), COORDINACIO_IONI)) { int k = 1; while (k < 4 && i - j - k > 0 && (matchPostagRegexp(tokens[i - j - k], KEEP_COUNT) || matchRegexp(tokens[i - j - k].getToken(), KEEP_COUNT2) || matchPostagRegexp(tokens[i - j - k], ADVERBIS_ACCEPTATS)) && (!matchRegexp(tokens[i - j - k].getToken(), STOP_COUNT))) { if (matchPostagRegexp(tokens[i - j - k], PREPOSICIONS)) { j = j + k; break; } k++; } }*/ // deux ou plus if (matchRegexp(tokens[i - j].getToken(), COORDINACIO_IONI)) { if (i - j - 1 > 0 && i - j + 1 < tokens.length) { if (matchPostagRegexp(tokens[i - j - 1], DET) && tokens[i - j + 1].getToken().equals("plus")) { j = j + 1; } } } return j; } private boolean keepCounting(AnalyzedTokenReadings aTr) { if (matchRegexp(aTr.getToken(), PREPOSICIO_CANVI_NIVELL)) { return true; } if (aTr.getToken().equals(".")) { //it is not sentence end, but abbreviation return true; } // stop searching if there is some of these combinations: // adverb+comma, adverb+conjunction, comma+conjunction, // punctuation+punctuation if ((adverbAppeared && conjunctionAppeared) || (adverbAppeared && punctuationAppeared) || (conjunctionAppeared && punctuationAppeared) || (punctuationAppeared && matchPostagRegexp(aTr, PUNTUACIO)) || (infinitiveAppeared && matchRegexp(aTr.getToken(), COORDINACIO_IONI)) || (infinitiveAppeared && adverbAppeared)) { return false; } return (matchPostagRegexp(aTr, KEEP_COUNT) || matchRegexp(aTr.getToken(), KEEP_COUNT2) || matchPostagRegexp(aTr, ADVERBIS_ACCEPTATS)) && !matchRegexp(aTr.getToken(), STOP_COUNT) && (!matchPostagRegexp(aTr, GV) || matchPostagRegexp(aTr, _GN_)); } private void initializeApparitions() { adverbAppeared = false; conjunctionAppeared = false; punctuationAppeared = false; infinitiveAppeared = false; } private void updateApparitions(AnalyzedTokenReadings aTr) { conjunctionAppeared |= matchPostagRegexp(aTr, CONJUNCIO); if (aTr.getToken().equals("com")) { return; } if (matchPostagRegexp(aTr, NOM) || matchPostagRegexp(aTr, ADJECTIU)) { initializeApparitions(); return; } adverbAppeared |= matchPostagRegexp(aTr, ADVERBI); punctuationAppeared |= (matchPostagRegexp(aTr, PUNTUACIO) || aTr.getToken().equals(",")); infinitiveAppeared |= matchPostagRegexp(aTr, INFINITIVE); } /** * Match POS tag with regular expression */ private boolean matchPostagRegexp(AnalyzedTokenReadings aToken, Pattern pattern) { boolean matches = false; for (AnalyzedToken analyzedToken : aToken) { String posTag = analyzedToken.getPOSTag(); if (posTag == null) { posTag = "UNKNOWN"; } final Matcher m = pattern.matcher(posTag); if (m.matches()) { matches = true; break; } } return matches; } /** * Match String with regular expression */ private boolean matchRegexp(String s, Pattern pattern) { final Matcher m = pattern.matcher(s); return m.matches(); } private AnalyzedToken getAnalyzedToken(AnalyzedTokenReadings aToken, Pattern pattern) { for (AnalyzedToken analyzedToken : aToken) { String posTag = analyzedToken.getPOSTag(); if (posTag == null) { posTag = "UNKNOWN"; } final Matcher m = pattern.matcher(posTag); if (m.matches()) { return analyzedToken; } } return null; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1228"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.safehaus.subutai.core.tracker.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import org.safehaus.subutai.common.tracker.ProductOperation; import org.safehaus.subutai.common.tracker.ProductOperationState; import org.safehaus.subutai.common.tracker.ProductOperationView; import org.safehaus.subutai.core.db.api.DBException; import org.safehaus.subutai.core.db.api.DbManager; import org.safehaus.subutai.core.tracker.api.Tracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; /** * This is an implementation of Tracker */ public class TrackerImpl implements Tracker { /** * Used to serialize/deserialize product operation to/from json format */ private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); private static final Logger LOG = LoggerFactory.getLogger( TrackerImpl.class.getName() ); private static final String SOURCE_IS_EMPTY_MSG = "Source is null or empty"; /** * reference to dbmanager */ private DbManager dbManager; public void setDbManager( DbManager dbManager ) { Preconditions.checkNotNull( dbManager, "Db manager is null" ); this.dbManager = dbManager; } /** * Get view of product operation by operation id * * @param source - source of product operation, usually this is a module name * @param operationTrackId - id of operation * * @return - product operation view */ public ProductOperationView getProductOperation( String source, UUID operationTrackId ) { Preconditions.checkArgument( !Strings.isNullOrEmpty( source ), SOURCE_IS_EMPTY_MSG ); Preconditions.checkNotNull( operationTrackId, "Operation track id is null" ); try { ResultSet rs = dbManager.executeQuery2( "select info from product_operation where source = ? and id = ?", source.toLowerCase(), operationTrackId ); return constructProductOperation( rs.one() ); } catch ( DBException | JsonSyntaxException ex ) { LOG.error( "Error in getProductOperation", ex ); } return null; } private ProductOperationViewImpl constructProductOperation( Row row ) { if ( row != null ) { String info = row.getString( "info" ); ProductOperationImpl po = GSON.fromJson( info, ProductOperationImpl.class ); return new ProductOperationViewImpl( po ); } return null; } /** * Saves product operation o DB * * @param source - source of product operation, usually this is a module * @param po - product operation * * @return - true if all went well, false otherwise */ boolean saveProductOperation( String source, ProductOperationImpl po ) { Preconditions.checkArgument( !Strings.isNullOrEmpty( source ), SOURCE_IS_EMPTY_MSG ); Preconditions.checkNotNull( po, "Product operation is null" ); try { dbManager.executeUpdate2( "insert into product_operation(source,id,info) values(?,?,?)", source.toLowerCase(), po.getId(), GSON.toJson( po ) ); return true; } catch ( DBException e ) { LOG.error( "Error in saveProductOperation", e ); } return false; } /** * Creates product operation and save it to DB * * @param source - source of product operation, usually this is a module * @param description - description of operation * * @return - returns created product operation */ public ProductOperation createProductOperation( String source, String description ) { Preconditions.checkArgument( !Strings.isNullOrEmpty( source ), SOURCE_IS_EMPTY_MSG ); Preconditions.checkNotNull( !Strings.isNullOrEmpty( description ), "Description is null or empty" ); ProductOperationImpl po = new ProductOperationImpl( source.toLowerCase(), description, this ); if ( saveProductOperation( source, po ) ) { return po; } return null; } /** * Returns list of product operations (views) filtering them by date interval * * @param source - source of product operation, usually this is a module * @param fromDate - beginning date of filter * @param toDate - ending date of filter * @param limit - limit of records to return * * @return - list of product operation views */ public List<ProductOperationView> getProductOperations( String source, Date fromDate, Date toDate, int limit ) { Preconditions.checkArgument( limit > 0, "Limit must be greater than 0" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( source ), SOURCE_IS_EMPTY_MSG ); Preconditions.checkNotNull( fromDate, "From Date is null" ); Preconditions.checkNotNull( toDate, "To Date is null" ); List<ProductOperationView> list = new ArrayList<>(); try { ResultSet rs = dbManager.executeQuery2( "select info from product_operation where source = ?" + " and id >= maxTimeuuid(?)" + " and id <= minTimeuuid(?)" + " order by id desc limit ?", source.toLowerCase(), fromDate, toDate, limit ); for ( Row row : rs ) { ProductOperationViewImpl productOperationViewImpl = constructProductOperation( row ); if ( row != null ) { list.add( productOperationViewImpl ); } } } catch ( DBException | JsonSyntaxException ex ) { LOG.error( "Error in getProductOperations", ex ); } return list; } /** * Returns list of all sources of product operations for which product operations exist in DB * * @return list of product operation sources */ public List<String> getProductOperationSources() { List<String> sources = new ArrayList<>(); try { ResultSet rs = dbManager.executeQuery2( "select distinct source from product_operation" ); for ( Row row : rs ) { String source = row.getString( "source" ); if ( !Strings.isNullOrEmpty( source ) ) { sources.add( source.toLowerCase() ); } } } catch ( DBException e ) { LOG.error( "Error in getProductOperationSources", e ); } return sources; } /** * Prints log of product operation to std out stream * * @param operationTrackId - id of operation * @param maxOperationDurationMs - max operation duration timeout after which printing ceases */ @Override public void printOperationLog( String source, UUID operationTrackId, long maxOperationDurationMs ) { int logSize = 0; long startedTs = System.currentTimeMillis(); while ( !Thread.interrupted() ) { ProductOperationView po = getProductOperation( source.toLowerCase(), operationTrackId ); if ( po != null ) { //print log if anything new is appended to it if ( logSize != po.getLog().length() ) { LOG.info( po.getLog().substring( logSize, po.getLog().length() ) ); logSize = po.getLog().length(); } //return if operation is completed //or if time limit is reached if ( po.getState() != ProductOperationState.RUNNING || System.currentTimeMillis() - startedTs > maxOperationDurationMs) { return; } try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { return; } } else { LOG.warn( "Product operation not found" ); return; } } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1229"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.laladev.moneyjinn.server.controller.capitalsource; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.laladev.moneyjinn.core.error.ErrorCode; import org.laladev.moneyjinn.core.rest.model.ErrorResponse; import org.laladev.moneyjinn.core.rest.model.capitalsource.CreateCapitalsourceRequest; import org.laladev.moneyjinn.core.rest.model.capitalsource.CreateCapitalsourceResponse; import org.laladev.moneyjinn.core.rest.model.transport.CapitalsourceTransport; import org.laladev.moneyjinn.core.rest.model.transport.ValidationItemTransport; import org.laladev.moneyjinn.model.access.GroupID; import org.laladev.moneyjinn.model.access.UserID; import org.laladev.moneyjinn.model.capitalsource.Capitalsource; import org.laladev.moneyjinn.model.capitalsource.CapitalsourceID; import org.laladev.moneyjinn.model.capitalsource.CapitalsourceState; import org.laladev.moneyjinn.model.capitalsource.CapitalsourceType; import org.laladev.moneyjinn.server.builder.CapitalsourceTransportBuilder; import org.laladev.moneyjinn.server.builder.GroupTransportBuilder; import org.laladev.moneyjinn.server.builder.UserTransportBuilder; import org.laladev.moneyjinn.server.builder.ValidationItemTransportBuilder; import org.laladev.moneyjinn.server.controller.AbstractControllerTest; import org.laladev.moneyjinn.service.api.IAccessRelationService; import org.laladev.moneyjinn.service.api.ICapitalsourceService; import org.springframework.http.HttpMethod; import org.springframework.test.context.jdbc.Sql; public class CreateCapitalsourceTest extends AbstractControllerTest { @Inject ICapitalsourceService capitalsourceService; @Inject IAccessRelationService accessRelationService; private final HttpMethod method = HttpMethod.POST; private String userName; private String userPassword; @Before public void setUp() { this.userName = UserTransportBuilder.USER1_NAME; this.userPassword = UserTransportBuilder.USER1_PASSWORD; } @Override protected String getUsername() { return this.userName; } @Override protected String getPassword() { return this.userPassword; } @Override protected String getUsecase() { return super.getUsecaseFromTestClassName(this.getClass()); } private void testError(final CapitalsourceTransport transport, final ErrorCode errorCode) throws Exception { final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest(); request.setCapitalsourceTransport(transport); final List<ValidationItemTransport> validationItems = new ArrayList<>(); validationItems .add(new ValidationItemTransportBuilder().withKey(null).withError(errorCode.getErrorCode()).build()); final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse(); expected.setValidationItemTransports(validationItems); expected.setResult(Boolean.FALSE); final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false, CreateCapitalsourceResponse.class); Assert.assertEquals(expected, actual); } @Test public void test_CapitalsourcenameAlreadyExisting_Error() throws Exception { final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); transport.setComment(CapitalsourceTransportBuilder.CAPITALSOURCE1_COMMENT); this.testError(transport, ErrorCode.NAME_ALREADY_EXISTS); } @Test public void test_emptyCapitalsourcename_Error() throws Exception { final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); transport.setComment(""); this.testError(transport, ErrorCode.COMMENT_IS_NOT_SET); } @Test public void test_nullCapitalsourcename_Error() throws Exception { final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); transport.setComment(null); this.testError(transport, ErrorCode.COMMENT_IS_NOT_SET); } @Test public void test_ToLongAccountnumber_Error() throws Exception { final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); transport.setAccountNumber("12345678901234567890123456789012345"); this.testError(transport, ErrorCode.ACCOUNT_NUMBER_TO_LONG); } @Test public void test_ToLongBankcode_Error() throws Exception { final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); transport.setBankCode("123456789012"); this.testError(transport, ErrorCode.BANK_CODE_TO_LONG); } @Test public void test_AccountnumberInvalidChar_Error() throws Exception { final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); transport.setAccountNumber("+"); this.testError(transport, ErrorCode.ACCOUNT_NUMBER_CONTAINS_ILLEGAL_CHARS); } @Test public void test_BankcodeInvalidChar_Error() throws Exception { final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); transport.setBankCode("+"); this.testError(transport, ErrorCode.BANK_CODE_CONTAINS_ILLEGAL_CHARS); } @Test public void test_standardRequest_SuccessfullNoContent() throws Exception { final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest(); final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); request.setCapitalsourceTransport(transport); final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse(); expected.setCapitalsourceId(CapitalsourceTransportBuilder.NEXT_ID); final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false, CreateCapitalsourceResponse.class); Assert.assertEquals(expected, actual); final UserID userId = new UserID(UserTransportBuilder.USER1_ID); final GroupID groupId = new GroupID(GroupTransportBuilder.GROUP1_ID); final CapitalsourceID capitalsourceId = new CapitalsourceID(CapitalsourceTransportBuilder.NEXT_ID); final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId, groupId, capitalsourceId); Assert.assertEquals(CapitalsourceTransportBuilder.NEXT_ID, capitalsource.getId().getId()); Assert.assertEquals(CapitalsourceTransportBuilder.NEWCAPITALSOURCE_COMMENT, capitalsource.getComment()); } @Test public void test_Bic8Digits_fillesUpTo11Digits() throws Exception { final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest(); final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); transport.setBankCode("ABCDEFGH"); request.setCapitalsourceTransport(transport); final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse(); expected.setCapitalsourceId(CapitalsourceTransportBuilder.NEXT_ID); final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false, CreateCapitalsourceResponse.class); Assert.assertEquals(expected, actual); final UserID userId = new UserID(UserTransportBuilder.USER1_ID); final GroupID groupId = new GroupID(GroupTransportBuilder.GROUP1_ID); final CapitalsourceID capitalsourceId = new CapitalsourceID(CapitalsourceTransportBuilder.NEXT_ID); final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId, groupId, capitalsourceId); Assert.assertEquals(CapitalsourceTransportBuilder.NEXT_ID, capitalsource.getId().getId()); Assert.assertEquals(CapitalsourceTransportBuilder.NEWCAPITALSOURCE_COMMENT, capitalsource.getComment()); Assert.assertEquals(transport.getBankCode() + "XXX", capitalsource.getBankAccount().getBankCode()); } @Test public void test_differentUserIdSet_ButIgnoredAndAlwaysCreatedWithOwnUserId() throws Exception { final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest(); final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); transport.setUserid(UserTransportBuilder.ADMIN_ID); request.setCapitalsourceTransport(transport); final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse(); expected.setCapitalsourceId(CapitalsourceTransportBuilder.NEXT_ID); final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false, CreateCapitalsourceResponse.class); Assert.assertEquals(expected, actual); final UserID userId = new UserID(UserTransportBuilder.USER1_ID); final GroupID groupId = new GroupID(GroupTransportBuilder.GROUP1_ID); final CapitalsourceID capitalsourceId = new CapitalsourceID(CapitalsourceTransportBuilder.NEXT_ID); final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId, groupId, capitalsourceId); Assert.assertEquals(CapitalsourceTransportBuilder.NEXT_ID, capitalsource.getId().getId()); Assert.assertEquals(CapitalsourceTransportBuilder.NEWCAPITALSOURCE_COMMENT, capitalsource.getComment()); } @Test public void test_checkDefaults_SuccessfullNoContent() throws Exception { final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest(); final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); transport.setValidFrom(null); transport.setValidTil(null); transport.setState(null); transport.setType(null); transport.setAccountNumber(null); transport.setBankCode(null); request.setCapitalsourceTransport(transport); final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse(); expected.setCapitalsourceId(CapitalsourceTransportBuilder.NEXT_ID); final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false, CreateCapitalsourceResponse.class); Assert.assertEquals(expected, actual); final UserID userId = new UserID(UserTransportBuilder.USER1_ID); final GroupID groupId = new GroupID(GroupTransportBuilder.GROUP1_ID); final CapitalsourceID capitalsourceId = new CapitalsourceID(CapitalsourceTransportBuilder.NEXT_ID); final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId, groupId, capitalsourceId); Assert.assertEquals(CapitalsourceTransportBuilder.NEXT_ID, capitalsource.getId().getId()); Assert.assertEquals(CapitalsourceTransportBuilder.NEWCAPITALSOURCE_COMMENT, capitalsource.getComment()); Assert.assertEquals(CapitalsourceState.CACHE, capitalsource.getState()); Assert.assertEquals(CapitalsourceType.CURRENT_ASSET, capitalsource.getType()); Assert.assertEquals(LocalDate.now(), capitalsource.getValidFrom()); Assert.assertEquals(LocalDate.parse("2999-12-31"), capitalsource.getValidTil()); Assert.assertNull(capitalsource.getBankAccount()); } @Test public void test_AuthorizationRequired_Error() throws Exception { this.userName = null; this.userPassword = null; final ErrorResponse actual = super.callUsecaseWithoutContent("", this.method, false, ErrorResponse.class); Assert.assertEquals(super.accessDeniedErrorResponse(), actual); } @Test @Sql("classpath:h2defaults.sql") public void test_emptyDatabase_noException() throws Exception { this.userName = UserTransportBuilder.ADMIN_NAME; this.userPassword = UserTransportBuilder.ADMIN_PASSWORD; final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest(); final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build(); request.setCapitalsourceTransport(transport); final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse(); expected.setCapitalsourceId(1L); final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false, CreateCapitalsourceResponse.class); Assert.assertEquals(expected, actual); final UserID userId = new UserID(UserTransportBuilder.ADMIN_ID); final GroupID groupId = new GroupID(GroupTransportBuilder.ADMINGROUP_ID); final CapitalsourceID capitalsourceId = new CapitalsourceID(1l); final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId, groupId, capitalsourceId); Assert.assertEquals(new Long(1l), capitalsource.getId().getId()); Assert.assertEquals(CapitalsourceTransportBuilder.NEWCAPITALSOURCE_COMMENT, capitalsource.getComment()); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1230"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.planetmayo.debrief.satc.model.contributions; import java.awt.geom.Point2D; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.Status; import com.planetmayo.debrief.satc.model.GeoPoint; import com.planetmayo.debrief.satc.model.generator.IContributions; import com.planetmayo.debrief.satc.model.legs.CoreRoute; import com.planetmayo.debrief.satc.model.legs.LegType; import com.planetmayo.debrief.satc.model.states.BaseRange.IncompatibleStateException; import com.planetmayo.debrief.satc.model.states.BoundedState; import com.planetmayo.debrief.satc.model.states.LocationRange; import com.planetmayo.debrief.satc.model.states.ProblemSpace; import com.planetmayo.debrief.satc.model.states.State; import com.planetmayo.debrief.satc.util.GeoSupport; import com.planetmayo.debrief.satc.util.MathUtils; import com.planetmayo.debrief.satc.util.ObjectUtils; import com.planetmayo.debrief.satc.util.calculator.GeodeticCalculator; import com.planetmayo.debrief.satc.zigdetector.ILegStorer; import com.planetmayo.debrief.satc.zigdetector.LegOfData; import com.planetmayo.debrief.satc.zigdetector.OwnshipLegDetector; import com.planetmayo.debrief.satc.zigdetector.Sensor; import com.planetmayo.debrief.satc.zigdetector.ZigDetector; import com.planetmayo.debrief.satc_rcp.SATC_Activator; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.LinearRing; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.geom.impl.CoordinateArraySequence; public class BearingMeasurementContribution extends CoreMeasurementContribution<BearingMeasurementContribution.BMeasurement> { private static final long serialVersionUID = 1L; public static final String BEARING_ERROR = "bearingError"; public static final String RUN_MDA = "autoDetect"; public static interface MDAResultsListener{ public void sliced(String string, List<LegOfData> ownshipLegs, ArrayList<StraightLegForecastContribution> arrayList, ArrayList<HostState> hostStates); } /** * the allowable bearing error (in radians) * */ private Double bearingError = 0d; /** * flag for whether this contribution should run an MDA on the data * */ private boolean runMDA = true; /** store the ownship states, if possible. We use this to run the * manoeuvre detection algorithm */ private ArrayList<HostState> states; /** array of listeners interested in MDA * */ private transient ArrayList<MDAResultsListener> _listeners = null; @Override public void actUpon(ProblemSpace space) throws IncompatibleStateException { // ok, here we really go for it! Iterator<BMeasurement> iter = measurements.iterator(); // sort out a geometry factory GeometryFactory factory = GeoSupport.getFactory(); while (iter.hasNext()) { BearingMeasurementContribution.BMeasurement measurement = iter.next(); // is it active? if (measurement.isActive()) { // ok, create the polygon for this measurement GeoPoint origin = measurement.origin; double bearing = measurement.bearingAngle; double range = measurement.range; // sort out the left/right edges double leftEdge = bearing - bearingError; double rightEdge = bearing + bearingError; // ok, generate the polygon Coordinate[] coords = new Coordinate[5]; // start off with the origin final double lon = origin.getLon(); final double lat = origin.getLat(); coords[0] = new Coordinate(lon, lat); // create a utility object to help with calcs GeodeticCalculator calc = GeoSupport.createCalculator(); // now the top-left calc.setStartingGeographicPoint(new Point2D.Double(lon, lat)); calc.setDirection(Math.toDegrees(MathUtils.normalizeAngle2(leftEdge)), range); Point2D dest = calc.getDestinationGeographicPoint(); coords[1] = new Coordinate(dest.getX(), dest.getY()); // now the centre bearing calc.setStartingGeographicPoint(new Point2D.Double(lon, lat)); calc.setDirection(Math.toDegrees(MathUtils.normalizeAngle2(bearing)), range); dest = calc.getDestinationGeographicPoint(); coords[2] = new Coordinate(dest.getX(), dest.getY()); // now the top-right calc.setStartingGeographicPoint(new Point2D.Double(lon, lat)); calc.setDirection(Math.toDegrees(MathUtils.normalizeAngle2(rightEdge)), range); dest = calc.getDestinationGeographicPoint(); coords[3] = new Coordinate(dest.getX(), dest.getY()); // and back to the start coords[4] = new Coordinate(coords[0]); // ok, store the coordinates CoordinateArraySequence seq = new CoordinateArraySequence(coords); // and construct the bounded location object LinearRing ls = new LinearRing(seq, factory); Polygon poly = new Polygon(ls, null, factory); LocationRange lr = new LocationRange(poly); // do we have a bounds at this time? BoundedState thisState = space.getBoundedStateAt(measurement.time); if (thisState == null) { // ok, do the bounds thisState = new BoundedState(measurement.time); // and store it space.add(thisState); } // ok, override any existing color for this state, if we have one if (measurement.getColor() != null) thisState.setColor(measurement.getColor()); // well, if we didn't - we do now! Apply it! thisState.constrainTo(lr); LineString bearingLine = GeoSupport.getFactory().createLineString( new Coordinate[] { coords[0], coords[2] }); thisState.setBearingLine(bearingLine); // also store the bearing value in the state - since it's of value in // other processes (1959) thisState.setBearingValue(bearing); } } // hmm, do we run the MDA? if (getAutoDetect()) { // get a few bounded states Collection<BoundedState> testStates = space.getBoundedStatesBetween( this.getStartDate(), this.getFinishDate()); int ctr = 0; for (Iterator<BoundedState> iterator = testStates.iterator(); iterator .hasNext();) { BoundedState boundedState = iterator.next(); ctr++; if (ctr >= 0 && ctr <= 3) { boundedState.setMemberOf("test MDA leg"); } } } } @Override protected double cumulativeScoreFor(CoreRoute route) { double bearingError = this.bearingError == null ? 0 : this.bearingError; if (!isActive() || route.getType() == LegType.ALTERING || bearingError == 0) { return 0; } double res = 0; int count = 0; for (BMeasurement measurement : measurements) { Date dateMeasurement = measurement.getDate(); if (dateMeasurement.compareTo(route.getStartTime()) >= 0 && dateMeasurement.compareTo(route.getEndTime()) <= 0) { State state = route.getStateAt(dateMeasurement); if (state != null && state.getLocation() != null) { GeodeticCalculator calculator = GeoSupport.createCalculator(); calculator.setStartingGeographicPoint(measurement.origin.getLon(), measurement.origin.getLat()); calculator.setDestinationGeographicPoint(state.getLocation().getX(), state.getLocation().getY()); double radians = MathUtils.normalizeAngle(Math.toRadians(calculator .getAzimuth())); double angleDiff = MathUtils.angleDiff(measurement.bearingAngle, radians, true); // make the error a proportion of the bearing error angleDiff = angleDiff / (this.getBearingError()); // store the error state.setScore(this, angleDiff * this.getWeight() / 10); // and prepare the cumulative score double thisError = angleDiff * angleDiff; res += thisError; count++; } } } if (count > 0) { res = Math.sqrt(res / count) / bearingError; } return res; } public void addMeasurement(double lat, double lon, Date date, double brg, double range) { GeoPoint loc = new GeoPoint(lat, lon); BMeasurement measure = new BMeasurement(loc, brg, date, range); addMeasurement(measure); } public void loadFrom(List<String> lines) { // load from this source // ;;IGNORE YYMMDD HHMMSS IGNORE IGNORE LAT_DEG LAT_MIN LAT_SEC LAT_HEM // LONG_DEG LONG_MIN LONG_SEC LONG_HEM BEARING MAX_RNG // ;SENSOR: 100112 121329 SENSOR @A 0 3 57.38 S 30 0 8.65 W 1.5 15000 // Read File Line By Line for (String strLine : lines) { // hey, is this a comment line? if (strLine.startsWith(";;")) { continue; } // ok, get parseing it String[] elements = strLine.split("\\s+"); // now the date String date = elements[1]; // and the time String time = elements[2]; String latDegs = elements[5]; String latMins = elements[6]; String latSecs = elements[7]; String latHemi = elements[8]; String lonDegs = elements[9]; String lonMins = elements[10]; String lonSecs = elements[11]; String lonHemi = elements[12]; // and the beraing String bearing = elements[13]; // and the range String range = elements[14]; // ok,now construct the date=time Date theDate = ObjectUtils.safeParseDate(new SimpleDateFormat( "yyMMdd HHmmss"), date + " " + time); // and the location double lat = Double.valueOf(latDegs) + Double.valueOf(latMins) / 60d + Double.valueOf(latSecs) / 60d / 60d; if (latHemi.toUpperCase().equals("S")) lat = -lat; double lon = Double.valueOf(lonDegs) + Double.valueOf(lonMins) / 60d + Double.valueOf(lonSecs) / 60d / 60d; if (lonHemi.toUpperCase().equals("W")) lon = -lon; GeoPoint theLoc = new GeoPoint(lat, lon); double angle = Math.toRadians(Double.parseDouble(bearing)); BMeasurement measure = new BMeasurement(theLoc, angle, theDate, Double.parseDouble(range)); addMeasurement(measure); } this.setBearingError(Math.toRadians(3d)); } /** * get the bearing error * * @param errorRads * (in radians) */ public Double getBearingError() { return bearingError; } public List<HostState> getHostState() { return states; } /** * provide the bearing error * * @return (in radians) */ public void setBearingError(Double errorRads) { // IDIOT CHECK - CHECK WE HAVEN'T ACCIDENTALLY GOT DEGREES if (errorRads > 2) SATC_Activator.log(Status.WARNING, "Looks like error is being presented in Degs", null); Double old = bearingError; this.bearingError = errorRads; firePropertyChange(BEARING_ERROR, old, errorRads); fireHardConstraintsChange(); } public void setAutoDetect(boolean onAuto) { boolean previous = runMDA; runMDA = onAuto; firePropertyChange(RUN_MDA, previous, onAuto); firePropertyChange(HARD_CONSTRAINTS, previous, onAuto); } public boolean getAutoDetect() { return runMDA; } /** * utility class for storing a measurement * * @author ian * */ public static class BMeasurement extends CoreMeasurementContribution.CoreMeasurement { private static final double MAX_RANGE_METERS = 50000.; private final GeoPoint origin; private final double bearingAngle; /** * the (optional) maximum range for this measurement * */ private final double range; public BMeasurement(GeoPoint loc, double bearing, Date time, Double range) { super(time); this.origin = loc; this.bearingAngle = MathUtils.normalizeAngle(bearing); // tidying up. Give the maximum possible range for this bearing if the // data is missing this.range = range == null ? MAX_RANGE_METERS : range; } } public long[] getTimes(ArrayList<HostState> states) { long[] res = new long[states.size()]; int ctr = 0; Iterator<HostState> iter = states.iterator(); while (iter.hasNext()) { BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter .next(); res[ctr++] = hostState.time; } return res; } public double[] getCourses(ArrayList<HostState> states) { double[] res = new double[states.size()]; Iterator<HostState> iter = states.iterator(); int ctr = 0; while (iter.hasNext()) { BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter .next(); res[ctr++] = hostState.courseDegs; } return res; } public double[] getSpeeds(ArrayList<HostState> states) { double[] res = new double[states.size()]; Iterator<HostState> iter = states.iterator(); int ctr = 0; while (iter.hasNext()) { BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter .next(); res[ctr++] = hostState.speedKts; } return res; } public static class HostState { final public long time; final public double courseDegs; final public double speedKts; public HostState(long time, double courseDegs, double speedKts) { this.time = time; this.courseDegs = courseDegs; this.speedKts = speedKts; } } public void runMDA(final IContributions contributions) { // ok, we've got to find the ownship data, somehow :-( if ((states == null) || (states.size() == 0)) { return; } // ok, extract the ownship legs from this data OwnshipLegDetector osLegDet = new OwnshipLegDetector(); List<LegOfData> ownshipLegs = osLegDet.identifyOwnshipLegs(getTimes(states), getCourses(states), getSpeeds(states), 5); // create object that can store the new legs MyLegStorer storer = new MyLegStorer(contributions); // ok, now collate the bearing data ZigDetector detector = new ZigDetector(); // ok, work through the legs. In the absence of a Discrete // Optimisation algorithm we're taking a brue force approach. // Hopefully we can find an optimised alternative to this. for (final Iterator<LegOfData> iterator2 = ownshipLegs.iterator(); iterator2 .hasNext();) { final LegOfData thisLeg = iterator2.next(); // ok, slice the data for this leg long legStart = thisLeg.getStart(); long legEnd = thisLeg.getEnd(); // trim the start/end to the sensor data legStart = Math.max(legStart, getStartDate().getTime()); legEnd = Math .min(legEnd, getFinishDate().getTime()); List<Long> thisLegTimes = new ArrayList<Long>(); List<Double> thisLegBearings = new ArrayList<Double>(); ArrayList<BMeasurement> meas = getMeasurements(); Iterator<BMeasurement> iter = meas.iterator(); while (iter.hasNext()) { BearingMeasurementContribution.BMeasurement measurement = (BearingMeasurementContribution.BMeasurement) iter .next(); long thisTime = measurement.getDate().getTime(); if((thisTime >= legStart) && (thisTime <= legEnd)) { thisLegTimes.add(measurement.getDate().getTime()); thisLegBearings.add(Math.toDegrees(measurement.bearingAngle)); } } detector.sliceThis("some name",legStart, legEnd, null, storer, 0.6, 0.000001, thisLegTimes, thisLegBearings); } // ok, slicing done! if(_listeners != null) { Iterator<MDAResultsListener> iter = _listeners.iterator(); while (iter.hasNext()) { BearingMeasurementContribution.MDAResultsListener thisL = (BearingMeasurementContribution.MDAResultsListener) iter .next(); thisL.sliced(getName(), ownshipLegs, storer.getSlices(), states); } } } public void addSliceListener(MDAResultsListener listener) { if(_listeners == null) _listeners = new ArrayList<MDAResultsListener>(); _listeners.add(listener); } public void removeSliceListener(MDAResultsListener listener) { if(_listeners != null) _listeners.remove(listener); } private static class MyLegStorer implements ILegStorer { int ctr = 1; private ArrayList<StraightLegForecastContribution> slices = new ArrayList<StraightLegForecastContribution>(); private final IContributions _contributions; public MyLegStorer(final IContributions theConts) { _contributions = theConts; } public ArrayList<StraightLegForecastContribution> getSlices() { return slices; } @Override public void storeLeg(String scenarioName, long tStart, long tEnd, Sensor sensor, double rms) { String name = "Leg-" + ctr++; SATC_Activator.log(Status.INFO, " FOUND LEG FROM " + new Date(tStart) + " - " + new Date(tEnd), null); StraightLegForecastContribution slf = new StraightLegForecastContribution(); slf.setStartDate(new Date(tStart)); slf.setFinishDate(new Date(tEnd)); slf.setActive(true); slf.setName(name); _contributions.addContribution(slf); slices .add(slf); } } public void addState(final HostState newState) { // check we have our states if (states == null) states = new ArrayList<HostState>(); // and store this new one states.add(newState); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1231"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.devgateway.toolkit.persistence.mongo.spring; import org.apache.commons.io.IOUtils; import org.devgateway.ocds.persistence.mongo.DefaultLocation; import org.devgateway.ocds.persistence.mongo.Organization; import org.devgateway.ocds.persistence.mongo.Release; import org.devgateway.ocds.persistence.mongo.flags.FlagsConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.ScriptOperations; import org.springframework.data.mongodb.core.index.Index; import org.springframework.data.mongodb.core.index.TextIndexDefinition.TextIndexDefinitionBuilder; import org.springframework.data.mongodb.core.script.ExecutableMongoScript; import org.springframework.data.mongodb.core.script.NamedMongoScript; import javax.annotation.PostConstruct; import java.io.IOException; import java.net.URL; @Configuration public class MongoTemplateConfiguration { private final Logger logger = LoggerFactory.getLogger(MongoTemplateConfiguration.class); @Autowired private MongoTemplate mongoTemplate; public void createMandatoryImportIndexes() { //mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("planning.budget.projectID", Direction.ASC)); //mongoTemplate.indexOps(Location.class).ensureIndex(new Index().on("description", Direction.ASC)); mongoTemplate.indexOps(Organization.class).ensureIndex(new Index().on("identifier._id", Direction.ASC)); mongoTemplate.indexOps(Organization.class) .ensureIndex(new Index().on("additionalIdentifiers._id", Direction.ASC)); mongoTemplate.indexOps(Organization.class).ensureIndex( new Index().on("roles", Direction.ASC)); mongoTemplate.indexOps(Organization.class).ensureIndex(new Index().on("name", Direction.ASC).unique()); mongoTemplate.indexOps(DefaultLocation.class).ensureIndex(new Index().on("description", Direction.ASC)); logger.info("Added mandatory Mongo indexes"); } public void createCorruptionFlagsIndexes() { mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("flags.flaggedStats", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("flags.eligibleStats", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on(FlagsConstants.I038_VALUE, Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on(FlagsConstants.I007_VALUE, Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on(FlagsConstants.I004_VALUE, Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on(FlagsConstants.I077_VALUE, Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on(FlagsConstants.I019_VALUE, Direction.ASC)); } @PostConstruct public void mongoPostInit() { createMandatoryImportIndexes(); createPostImportStructures(); } public void createPostImportStructures() { createCorruptionFlagsIndexes(); // initialize some extra indexes mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("ocid", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.procurementMethod", Direction.ASC)); mongoTemplate.indexOps(Release.class) .ensureIndex(new Index().on("tender.procurementMethodRationale", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.status", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("awards.status", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("awards.suppliers._id", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("awards.date", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("awards.value.amount", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.value.amount", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.numberOfTenderers", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.submissionMethod", Direction.ASC)); mongoTemplate.indexOps(Release.class) .ensureIndex(new Index().on("tender.tenderPeriod.startDate", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.tenderPeriod.endDate", Direction.ASC)); mongoTemplate.indexOps(Release.class) .ensureIndex(new Index().on("tender.items.classification._id", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index(). on("tender.items.deliveryLocation._id", Direction.ASC)); mongoTemplate.indexOps(Release.class).ensureIndex(new Index(). on("tender.items.deliveryLocation.geometry.coordinates", Direction.ASC)); mongoTemplate.indexOps(Organization.class).ensureIndex(new TextIndexDefinitionBuilder().onField("name") .onField("id").onField("additionalIdentifiers._id").build()); logger.info("Added extra Mongo indexes"); ScriptOperations scriptOps = mongoTemplate.scriptOps(); // add script to calculate the percentiles endpoint URL scriptFile = getClass().getResource("/tenderBidPeriodPercentilesMongo.js"); try { String scriptText = IOUtils.toString(scriptFile); ExecutableMongoScript script = new ExecutableMongoScript(scriptText); scriptOps.register(new NamedMongoScript("tenderBidPeriodPercentiles", script)); } catch (IOException e) { e.printStackTrace(); } // add general mongo system helper methods URL systemScriptFile = getClass().getResource("/mongoSystemScripts.js"); try { String systemScriptFileText = IOUtils.toString(systemScriptFile); ExecutableMongoScript script = new ExecutableMongoScript(systemScriptFileText); scriptOps.execute(script); } catch (IOException e) { e.printStackTrace(); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1232"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package eu.cloudscaleproject.env.toolchain.util; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Layout; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.views.properties.IPropertySheetPage; import eu.cloudscaleproject.env.common.ColorResources; import eu.cloudscaleproject.env.common.interfaces.IRefreshable; import eu.cloudscaleproject.env.common.interfaces.ISelectable; import eu.cloudscaleproject.env.common.ui.GradientComposite; import eu.cloudscaleproject.env.common.ui.HoverButton; import eu.cloudscaleproject.env.common.ui.HoverToggleButton; import eu.cloudscaleproject.env.common.ui.util.ColorHelper; import eu.cloudscaleproject.env.toolchain.IDirtyAdapter; import eu.cloudscaleproject.env.toolchain.IPropertySheetPageProvider; import eu.cloudscaleproject.env.toolchain.ProjectEditorSelectionService; import eu.cloudscaleproject.env.toolchain.resources.types.IEditorInput; import eu.cloudscaleproject.env.toolchain.resources.types.IEditorInputResource; public abstract class AbstractSidebarEditor implements ISidebarEditor{ //private static final Logger logger = Logger.getLogger(AbstractSidebarEditor.class.getName()); private StackLayout stackLayout; private final Composite compositeSidebar; private final Composite compositeArea; private Composite emptyPanel; private Composite compositeSidebarList = null; private Composite compositeSidebarControls = null; private boolean btnNewFromEnabled = true; private boolean btnNewEnabled = true; private boolean btnRemoveEnabled = true; protected final LinkedHashMap<IEditorInput, EditorItem> entries = new LinkedHashMap<IEditorInput, EditorItem>(); // user-implemented methods //////////// public abstract Composite createInputComposite(IEditorInput input, Composite parent, int style); public void handleNewInput(IEditorInput selected){}; public void handleNewInputFrom(IEditorInput selected){}; public void handleInputDelete(IEditorInput toDelete){}; public void handleSelect(IEditorInput selected){}; public class EditorItem implements IPropertySheetPageProvider{ private final IEditorInput input; private final String sectionName; private HoverToggleButton btnSelect; private Composite composite; private Color color_select; private Color color_hover; public boolean isSelected = false; final PropertyChangeListener eirChangeListener = new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { Display.getDefault().syncExec(new Runnable() { public void run() { resourceChanged(evt); }; }); // When non GUI thread => WorkbenchWidow == null if (Display.getDefault().getThread() != Thread.currentThread()) return; IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); if(editor != null){ IDirtyAdapter dirtyAdapter = (IDirtyAdapter)editor.getAdapter(IDirtyAdapter.class); if(dirtyAdapter != null){ dirtyAdapter.fireDirtyState(); } } } }; public EditorItem(IEditorInput input, String sectionName, int style) { this.input = input; this.sectionName = sectionName; initialize(); this.input.addPropertyChangeListener(eirChangeListener); EditorRegistry.getInstance().registerEditorItem(AbstractSidebarEditor.this, EditorItem.this); } public void resourceChanged(PropertyChangeEvent evt){ if(composite == null || composite.isDisposed()){ return; } if(btnSelect == null || btnSelect.isDisposed()){ return; } if (IEditorInputResource.PROP_LOADED.equals(evt.getPropertyName())) { btnSelect.setText(input.getName()); btnSelect.redraw(); if(composite instanceof IRefreshable){ ((IRefreshable)composite).refresh(); } } if(IEditorInputResource.PROP_NAME.equals(evt.getPropertyName())){ btnSelect.setText((String)evt.getNewValue()); btnSelect.redraw(); } } public IEditorInput getInput() { return input; } public Composite getComposite() { return composite; } private List<ISaveable> getSaveables(){ List<ISaveable> out = new ArrayList<>(); collectSaveableComposites(out, composite); return out; } public boolean isDirty(){ if(this.input instanceof IEditorInputResource){ IEditorInputResource res = (IEditorInputResource)input; return res.isDirty(); } for(ISaveable s : getSaveables()){ if(s.isDirty()){ return true; } } return false; } private void collectSaveableComposites(List<ISaveable> composites, Composite c){ if(c == null || c.isDisposed()){ return; } if(c instanceof ISaveable){ composites.add((ISaveable)c); return; } for(Control control : c.getChildren()){ if(control instanceof Composite){ collectSaveableComposites(composites, (Composite)control); } } } public void save(){ BusyIndicator.showWhile(Display.getDefault(), new Runnable() { @Override public void run() { if(input instanceof IEditorInputResource){ IEditorInputResource res = (IEditorInputResource)input; if(res.isDirty()){ res.save(); } } for(ISaveable s : getSaveables()){ if(s.isDirty()){ s.save(); } } } }); } public void load(final boolean force){ BusyIndicator.showWhile(Display.getDefault(), new Runnable() { @Override public void run() { if(input instanceof IEditorInputResource){ if(composite != null && !composite.isDisposed()){ composite.dispose(); } IEditorInputResource res = (IEditorInputResource)input; synchronized (res) { if(!res.isLoaded() || force){ res.load(); } } /* if(isSelected){ select(); } */ } } }); } private void initialize(){ BusyIndicator.showWhile(Display.getDefault(), new Runnable() { @Override public void run() { load(false); } }); initButton(); } private void checkWidgets(){ initButton(); initComposite(); } private void initButton(){ if(btnSelect == null || btnSelect.isDisposed()){ btnSelect = new HoverToggleButton(compositeSidebarList, SWT.NONE); Control c = getLastControlInSidebar(sectionName); if(c != null){ btnSelect.moveBelow(c); } btnSelect.setAlignmentHorizontal(SWT.LEFT); btnSelect.setIndentHorizontal(10); GridData gd_btnSelect = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); btnSelect.setLayoutData(gd_btnSelect); btnSelect.setText(input.getName()); //style if(color_select == null || color_select.isDisposed()){ color_select = ColorHelper.deviateSaturation(getSidebarBackgroundColor(), 0.1); } if(color_hover == null || color_hover.isDisposed()){ color_hover = ColorHelper.deviateValue(color_select, 0.1); } btnSelect.setBackground(getSidebarBackgroundColor()); btnSelect.setBackgroundSelected(color_select); btnSelect.setBackgroundHover(color_hover); btnSelect.setForeground(getSidebarForegroundColor()); btnSelect.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { select(); } }); btnSelect.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { EditorItem.this.dispose(); } }); } } private void initComposite(){ if(composite == null || composite.isDisposed()){ composite = createInputComposite(input, compositeArea, SWT.NONE); } } public void update() { checkWidgets(); if(composite instanceof IRefreshable){ ((IRefreshable)composite).refresh(); } btnSelect.setText(this.input.getName()); btnSelect.update(); } public void select(){ checkWidgets(); for(EditorItem ei : entries.values()){ ei.initButton(); ei.btnSelect.setSelection(false); ei.isSelected = false; } btnSelect.setSelection(true); stackLayout.topControl = composite; isSelected = true; update(); handleSelect(input); compositeArea.layout(); composite.setFocus(); ProjectEditorSelectionService.getInstance().reloadPropertySheetPage(); if(composite instanceof ISelectable){ ((ISelectable)composite).onSelect(); } } public void dispose() { input.removePropertyChangeListener(eirChangeListener); if(btnSelect != null){ btnSelect.dispose(); } if(composite != null){ composite.dispose(); } if(color_hover != null){ color_hover.dispose(); } if(color_select != null){ color_select.dispose(); } } @Override public IPropertySheetPage getPropertySheetPage() { if(composite instanceof IPropertySheetPageProvider){ IPropertySheetPageProvider propProvider = (IPropertySheetPageProvider)composite; return propProvider.getPropertySheetPage(); } return null; } } public AbstractSidebarEditor(Composite sidebar, Composite area) { this.compositeSidebar = sidebar; this.compositeArea = area; EditorRegistry.getInstance().registerEditor(this); } public Map<IEditorInput, EditorItem> getEntries() { return entries; } public void init(){ //dispose composites first dispose(); //rebuild side-bar items and area composites GridLayout gl_compositSidebar = new GridLayout(1, false); gl_compositSidebar.marginTop = 0; gl_compositSidebar.marginHeight = 0; gl_compositSidebar.marginWidth = 0; gl_compositSidebar.verticalSpacing = 0; compositeSidebar.setLayout(gl_compositSidebar); //composite that holds side-bar hover buttons compositeSidebarList = new GradientComposite(compositeSidebar, SWT.NONE); compositeSidebarList.setBackground(getSidebarBackgroundColor()); compositeSidebarList.setBounds(10, 10, 129, 280); GridLayout gl_compositSidebarList = new GridLayout(1, false); gl_compositSidebarList.marginTop = 0; gl_compositSidebarList.marginHeight = 0; gl_compositSidebarList.marginWidth = 1; gl_compositSidebarList.verticalSpacing = 1; compositeSidebarList.setLayout(gl_compositSidebarList); GridData gd_compositeSidebarList = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1); gd_compositeSidebarList.widthHint = 160; gd_compositeSidebarList.minimumWidth = 120; compositeSidebarList.setLayoutData(gd_compositeSidebarList); //create or retrieve stack layout of the area composite Layout areaLayout = compositeArea.getLayout(); if(areaLayout == null || !(areaLayout instanceof StackLayout)){ stackLayout = new StackLayout(); stackLayout.marginHeight = 0; compositeArea.setLayout(stackLayout); } else{ stackLayout = (StackLayout)areaLayout; } //create empty panel emptyPanel = createEmptyPanel(compositeArea); //create hover buttons and area composites from IEditorInput objects String[] sections = getSidebarSections(); if(sections != null){ for(String section : sections){ createSidebarSection(section, SWT.NONE); } } else{ createSidebarSection(null, SWT.NONE); } //select the first item or show the empty panel { Iterator<EditorItem> iter = entries.values().iterator(); if(iter.hasNext()){ iter.next().select(); } else{ stackLayout.topControl = emptyPanel; } } //rebuild controls composite initControls(); //layout recreated composites if(compositeSidebar != null && !compositeSidebar.isDisposed()){ compositeSidebar.layout(); } if(compositeArea != null && !compositeArea.isDisposed()){ compositeArea.layout(); } } private void initControls(){ if(compositeSidebarList == null || compositeSidebarList.isDisposed()){ return; } if(compositeSidebarControls != null){ compositeSidebarControls.dispose(); } compositeSidebarControls = new GradientComposite(compositeSidebar, SWT.NONE); compositeSidebarControls.setBackground(getSidebarBackgroundColor()); GridLayout gl_compositeControls = new GridLayout(1, false); gl_compositeControls.horizontalSpacing = 0; gl_compositeControls.verticalSpacing = 1; gl_compositeControls.marginWidth = 1; gl_compositeControls.marginHeight = 1; compositeSidebarControls.setLayout(gl_compositeControls); GridData gd_compositeControls = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1); gd_compositeControls.widthHint = 96; compositeSidebarControls.setLayoutData(gd_compositeControls); if(btnNewEnabled){ HoverButton btnNew = new HoverButton(compositeSidebarControls, SWT.NONE); btnNew.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); btnNew.setText("Create"); btnNew.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { EditorItem selected = getCurrentSelectionItem(); if(selected != null){ handleNewInput(selected.input); } else{ handleNewInput(null); } } }); } if(btnNewFromEnabled){ HoverButton btnNewFromSelection = new HoverButton(compositeSidebarControls, SWT.NONE); btnNewFromSelection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1)); btnNewFromSelection.setText("Clone"); btnNewFromSelection.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { EditorItem selected = getCurrentSelectionItem(); if(selected != null){ handleNewInputFrom(selected.input); } } }); } if(btnRemoveEnabled){ HoverButton btnRemove = new HoverButton(compositeSidebarControls, SWT.NONE); btnRemove.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); btnRemove.setText("Delete"); btnRemove.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { EditorItem selected = getCurrentSelectionItem(); if(selected != null){ handleInputDelete(selected.input); } } }); } } private Composite createEmptyPanel(Composite parent){ Composite c = new Composite(parent, SWT.NONE); FormLayout layout= new FormLayout(); layout.marginHeight = 5; layout.marginWidth = 5; c.setLayout(layout); Label label = new Label(c, SWT.NONE); label.setText("Currently there are no entries to display. Create new one?"); FormData lb_formData = new FormData(); lb_formData.top = new FormAttachment(0,30); lb_formData.left = new FormAttachment(15,0); label.setLayoutData(lb_formData); Button button = new Button(c, SWT.NONE); button.setText("Create new..."); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleNewInput(null); } }); FormData b_formData = new FormData(); b_formData.top = new FormAttachment(label, 5); b_formData.left = new FormAttachment(15,0); button.setLayoutData(b_formData); return c; } public EditorItem getCurrentSelectionItem(){ for(EditorItem ei : entries.values()){ if(ei.isSelected){ return ei; } } return null; } public int getCurrentSelectionIndex(){ int i = 0; for(EditorItem ei : entries.values()){ if(ei.isSelected){ return i; } i++; } return -1; } public void setCurrentSelectionIndex(int index){ int i = 0; for(EditorItem ei : entries.values()){ if(i == index){ ei.select(); return; } i++; } } public Composite getCurrentSelection(){ EditorItem ei = getCurrentSelectionItem(); if(ei != null){ return ei.composite; } return null; } @Override public void setNewButtonEnabled(boolean enable){ this.btnNewEnabled = enable; initControls(); } @Override public void setNewFromButtonEnabled(boolean enabled){ this.btnNewFromEnabled = enabled; initControls(); } @Override public void setRemoveButtonEnabled(boolean enabled){ this.btnRemoveEnabled = enabled; initControls(); } public void showInput(IEditorInput input){ EditorItem epc = entries.get(input); if(epc == null){ return; } epc.select(); } public void addSidebarEditor(IEditorInput ei, String section){ // Workaround - entry can already exist - thread fuck if (entries.get(ei) != null) return; EditorItem newEditorItem = new EditorItem(ei, section, SWT.NONE); entries.put(ei, newEditorItem); compositeArea.redraw(); compositeArea.layout(true); compositeSidebarList.redraw(); compositeSidebarList.layout(true); newEditorItem.select(); } public void removeSidebarEditor(IEditorInput editorInput){ //select another item int selIndex = getCurrentSelectionIndex(); int newIndex = selIndex > 0 ? selIndex - 1 : selIndex; EditorItem editorItem = entries.get(editorInput); if(editorItem != null){ editorItem.dispose(); } else{ //editor item already removed return; } entries.remove(editorInput); compositeArea.layout(true); compositeSidebarList.layout(true); if(newIndex < entries.size()){ setCurrentSelectionIndex(newIndex); } else{ stackLayout.topControl = emptyPanel; compositeArea.layout(); } } public void save(){ for(EditorItem ei : entries.values()){ ei.save(); } } public void load(boolean force){ EditorItem ei = getCurrentSelectionItem(); if(ei != null){ ei.load(force); } } public boolean isDirty(){ for(EditorItem ei : entries.values()){ if(ei.isDirty()){ return true; } } return false; } public void update(){ //update selection EditorItem selectedItem = getCurrentSelectionItem(); if(selectedItem != null){ selectedItem.update(); } compositeArea.update(); compositeSidebar.update(); } public Color getSidebarSectionBackgroundColor(){ return ColorResources.COLOR_CS_BLUE; } public Color getSidebarSectionForegroundColor(){ return ColorResources.COLOR_BLACK; } public Color getSidebarBackgroundColor(){ return ColorResources.COLOR_CS_BLUE_LIGHT; } public Color getSidebarForegroundColor(){ return ColorResources.COLOR_CS_BLUE_DARK; } private Control getLastControlInSidebar(String section){ Control out = null; boolean inSection = false; for(Control c : compositeSidebarList.getChildren()){ if(c instanceof Label){ Label l = (Label)c; if(l.getText().equals(section)){ inSection = true; } else{ inSection = false; } } if(inSection){ out = c; } } return out; } private void createSidebarSection(String sectionName, int style){ //generate section label if(sectionName != null){ final GradientComposite c = new GradientComposite(compositeSidebarList, SWT.NONE); c.setGradientDirection(false); c.setGradientColorStart(getSidebarSectionBackgroundColor()); c.setGradientColorEnd(getSidebarBackgroundColor()); c.setLayout(new GridLayout(1, false)); GridData gd_c = new GridData(SWT.FILL, SWT.FILL, true, false); gd_c.heightHint = 25; c.setLayoutData(gd_c); Label label = new Label(c, SWT.NONE); label.setForeground(getSidebarSectionForegroundColor()); label.setText(sectionName); label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); } //generate section entries List<IEditorInput> inputs = getInputs(sectionName); if(inputs != null){ for(IEditorInput input : inputs){ entries.put(input, new EditorItem(input, sectionName, style)); } } } @Override public IPropertySheetPage getPropertySheetPage() { EditorItem ei = getCurrentSelectionItem(); if(ei != null){ return ei.getPropertySheetPage(); } return null; } public void dispose() { for(EditorItem item : entries.values()){ item.dispose(); } entries.clear(); if(compositeSidebarList != null && !compositeSidebarList.isDisposed()){ compositeSidebarList.dispose(); } if(compositeSidebarControls != null && !compositeSidebarControls.isDisposed()){ compositeSidebarControls.dispose(); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1233"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.opencps.paymentmgt.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.opencps.paymentmgt.model.PaymentFile; import org.opencps.paymentmgt.service.base.PaymentFileLocalServiceBaseImpl; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.repository.model.FileEntry; import com.liferay.portal.kernel.util.OrderByComparator; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.model.User; import com.liferay.portal.security.permission.PermissionChecker; import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; import com.liferay.portal.security.permission.PermissionThreadLocal; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.service.UserLocalServiceUtil; /** * The implementation of the Payment file local service. * * <p> * All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link org.opencps.paymentmgt.service.PaymentFileLocalService} interface. * * <p> * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM. * </p> * * @author trungdk * @see org.opencps.paymentmgt.service.base.PaymentFileLocalServiceBaseImpl * @see org.opencps.paymentmgt.service.PaymentFileLocalServiceUtil */ public class PaymentFileLocalServiceImpl extends PaymentFileLocalServiceBaseImpl { /** * @param keypayTransactionId * @return * @throws PortalException * @throws SystemException */ public PaymentFile getByTransactionId(long keypayTransactionId) throws PortalException, SystemException { return paymentFilePersistence.fetchByT_I(keypayTransactionId); } /** * @param keypayGoodCode * @return * @throws PortalException * @throws SystemException */ public PaymentFile getByGoodCode(String keypayGoodCode) throws PortalException, SystemException { return paymentFilePersistence.fetchByG_C(keypayGoodCode); } /** * @param dossierId * @return * @throws PortalException * @throws SystemException */ public int countAllPaymentFile(long dossierId) throws PortalException, SystemException { return paymentFilePersistence.countByD_(dossierId); } /** * @param dossierId * @param paymentStatus * @return * @throws PortalException * @throws SystemException */ public int countPaymentFile(long dossierId, int paymentStatus) throws PortalException, SystemException { return paymentFilePersistence.countByD_P(dossierId, paymentStatus); } /* * NOTE FOR DEVELOPERS: * * Never reference this interface directly. Always use {@link org.opencps.paymentmgt.service.PaymentFileLocalServiceUtil} to access the Payment file local service. */ public PaymentFile addPaymentFile( long userId, long dossierId, long fileGroupId, long ownerUserId, long ownerOrganizationId, long govAgencyOrganizationId, String paymentName, Date requestDatetime, Double amount, String requestNote, String placeInfo, ServiceContext serviceContext) throws SystemException { long paymentFileId = counterLocalService.increment(PaymentFile.class.getName()); PaymentFile paymentFile = paymentFilePersistence.create(paymentFileId); Date now = new Date(); paymentFile.setUserId(userId); paymentFile.setGroupId(serviceContext.getScopeGroupId()); paymentFile.setCompanyId(serviceContext.getCompanyId()); paymentFile.setCreateDate(now); paymentFile.setModifiedDate(now); // paymentFile // .setUuid(PortalUUIDUtil // .generate()); paymentFile.setDossierId(dossierId); paymentFile.setFileGroupId(fileGroupId); paymentFile.setOwnerUserId(ownerUserId); paymentFile.setOwnerOrganizationId(ownerOrganizationId); paymentFile.setPaymentName(paymentName); paymentFile.setRequestDatetime(requestDatetime); paymentFile.setAmount(amount); paymentFile.setRequestNote(requestNote); paymentFile.setPlaceInfo(placeInfo); paymentFile.setPaymentStatus(0); paymentFile.setGovAgencyOrganizationId(govAgencyOrganizationId); // govAgencyOrganizationId > 0 insert // paymentFile.setGovAgencyTaxNo(govAgencyTaxNo); // paymentFile.setInvoiceTemplateNo(invoiceTemplateNo); // paymentFile.setInvoiceIssueNo(invoiceIssueNo); // paymentFile.setInvoiceNo(invoiceNo); return paymentFilePersistence.update(paymentFile); } public List<PaymentFile> searchPaymentFiles( long groupId, int paymentStatus, String keywords, int start, int end) { List<PaymentFile> listPaymentFile = new ArrayList<PaymentFile>(); try { listPaymentFile = paymentFileFinder.searchPaymentFiles( groupId, paymentStatus, keywords, start, end); } catch (SystemException e) { // TODO Auto-generated catch block _log.error(e); } return listPaymentFile; } public int countPaymentFiles( long groupId, int paymentStatus, String keywords) { try { return paymentFileFinder.countPaymentFiles( groupId, paymentStatus, keywords); } catch (SystemException e) { // TODO Auto-generated catch block _log.error(e); } return 0; } public int countCustomerPaymentFile( long groupId, String keyword, boolean isCitizen, long customerId, int paymentStatus) { return paymentFileFinder.countCustomerPaymentFile( groupId, keyword, isCitizen, customerId, paymentStatus); } public List<PaymentFile> searchCustomerPaymentFile( long groupId, String keyword, boolean isCitizen, long customerId, int paymentStatus, int start, int end, OrderByComparator obc) { return paymentFileFinder.searchCustomerPaymentFile( groupId, keyword, isCitizen, customerId, paymentStatus, start, end, obc); } public int countCustomerPaymentFileNewRequest( long groupId, String keyword, boolean isCitizen, long customerId, int[] paymentStatus) { return paymentFileFinder.countCustomerPaymentFileNewRequest( groupId, keyword, isCitizen, customerId, paymentStatus); } public List<PaymentFile> searchCustomerPaymentFileNewRequest( long groupId, String keyword, boolean isCitizen, long customerId, int[] paymentStatus, int start, int end, OrderByComparator obc) { return paymentFileFinder.searchCustomerPaymentFileNewRequest( groupId, keyword, isCitizen, customerId, paymentStatus, start, end, obc); } public PaymentFile getPaymentFileByGoodCode( long groupId, String keypayGoodCode) throws SystemException { return paymentFilePersistence.fetchByGoodCode(groupId, keypayGoodCode); } public PaymentFile getPaymentFileByMerchantResponse( long keypayTransactionId, String keypayGoodCode, double amount) throws SystemException { return paymentFilePersistence.fetchByMerchantResponse( keypayTransactionId, keypayGoodCode, amount); } /** * @param dossierId * @param fileGroupId * @param ownerUserId * @param ownerOrganizationId * @param govAgencyOrganizationId * @param paymentName * @param requestDatetime * @param amount * @param requestNote * @param placeInfo * @return * @throws SystemException */ public PaymentFile addPaymentFile( long dossierId, long fileGroupId, long ownerUserId, long ownerOrganizationId, long govAgencyOrganizationId, String paymentName, Date requestDatetime, Double amount, String requestNote, String placeInfo, String paymentOptions) throws SystemException { long paymentFileId = counterLocalService.increment(PaymentFile.class.getName()); PaymentFile paymentFile = paymentFilePersistence.create(paymentFileId); Date now = new Date(); paymentFile.setCreateDate(now); paymentFile.setModifiedDate(now); paymentFile.setDossierId(dossierId); paymentFile.setFileGroupId(fileGroupId); paymentFile.setOwnerUserId(ownerUserId); paymentFile.setOwnerOrganizationId(ownerOrganizationId); paymentFile.setPaymentName(paymentName); paymentFile.setRequestDatetime(requestDatetime); paymentFile.setAmount(amount); paymentFile.setRequestNote(requestNote); paymentFile.setPlaceInfo(placeInfo); paymentFile.setPaymentStatus(0); paymentFile.setPaymentOptions(paymentOptions); paymentFile.setGovAgencyOrganizationId(govAgencyOrganizationId); return paymentFilePersistence.update(paymentFile); } /** * @param paymentFileId * @param keypayUrl * @param keypayTransactionId * @param keypayGoodCode * @param keypayMerchantCode * @return * @throws PortalException * @throws SystemException */ public PaymentFile updatePaymentFile( long paymentFileId, String keypayUrl, long keypayTransactionId, String keypayGoodCode, String keypayMerchantCode) throws PortalException, SystemException { PaymentFile paymentFile = paymentFilePersistence.fetchByPrimaryKey(paymentFileId); paymentFile.setKeypayUrl(keypayUrl); paymentFile.setKeypayTransactionId(keypayTransactionId); paymentFile.setKeypayGoodCode(keypayGoodCode); paymentFile.setKeypayMerchantCode(keypayMerchantCode); paymentFilePersistence.update(paymentFile); return paymentFile; } public List<PaymentFile> getPaymentFileByD_(long dossierId) throws SystemException { return paymentFilePersistence.findByD_(dossierId); } public PaymentFile syncPaymentFile( String oid, String typeUpdate, int paymentStatus, int paymentMethod, String approveNote, byte[] bytes, long folderId, String sourceFileName, String mimeType, String title, String description, String changeLog, ServiceContext serviceContext) throws PortalException, SystemException { PaymentFile paymentFile = paymentFilePersistence.findByOID(oid); paymentFile.setPaymentStatus(paymentStatus); paymentFile.setPaymentMethod(paymentMethod); if (Validator.isNotNull(approveNote)) { paymentFile.setApproveNote(approveNote); } paymentFile.setApproveNote(approveNote); User user = UserLocalServiceUtil.getUser(serviceContext.getUserId()); PermissionChecker permissionChecker; try { permissionChecker = PermissionCheckerFactoryUtil.create(user); PermissionThreadLocal.setPermissionChecker(permissionChecker); } catch (Exception e) { } FileEntry fileEntry = dlAppLocalService.addFileEntry( serviceContext.getUserId(), serviceContext.getScopeGroupId(), folderId, sourceFileName, mimeType, title, description, changeLog, bytes, serviceContext); paymentFile.setConfirmFileEntryId(fileEntry.getFileEntryId()); paymentFilePersistence.update(paymentFile); return paymentFile; } private Log _log = LogFactoryUtil.getLog(PaymentFileLocalServiceImpl.class); }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1234"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.jtalks.poulpe.web.controller.component; import org.hibernate.validator.constraints.NotEmpty; import org.jtalks.common.model.entity.Component; import org.jtalks.common.model.entity.ComponentType; import org.jtalks.common.validation.ValidationException; import org.jtalks.poulpe.service.ComponentService; import org.jtalks.poulpe.web.controller.DialogManager; import org.jtalks.poulpe.web.controller.WindowManager; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.NotifyChange; import org.zkoss.util.resource.Labels; import org.zkoss.zk.ui.Executions; import javax.annotation.Nonnull; import java.util.HashMap; import java.util.List; import java.util.Map; /** * ViewModel class for EditComponent View * * @author Vahluev Vyacheslav */ public class EditCompViewModel { public static final String EMPTY_TITLE = "component.error.title_shouldnt_be_empty"; public static final String EMPTY_NAME = "component.error.name_shouldnt_be_empty"; public static final String ITEM_ALREADY_EXISTS = "item.already.exist"; /** * Current component we are working with */ private Component currentComponent = (Component) Executions.getCurrent().getDesktop() .getAttribute("componentToEdit"); /** * The name of the component */ private String name; /** * The description of the component */ private String description; /** * The name of the component */ private String componentName; /** * Type of the component */ private String componentType; /** * The caption of the forum */ private String caption; /** * The post preview size of the forum */ private String postPreviewSize; private String sessionTimeout; /** * Web-form validation messages */ private Map<String, String> validationMessages = new HashMap<String, String>(); protected ComponentService componentService; protected DialogManager dialogManager; protected WindowManager windowManager; /** * Sets the service instance which is used for manipulating with stored * components. * * @param componentService * the new value of the service instance */ public void setComponentService(ComponentService componentService) { this.componentService = componentService; } /** * Sets the dialog manager which is used for showing different types of * dialog messages. * * @param dialogManager * the new value of the dialog manager */ public void setDialogManager(DialogManager dialogManager) { this.dialogManager = dialogManager; } /** * Sets window manager. * * @param windowManager * the new window manager */ public void setWindowManager(WindowManager windowManager) { this.windowManager = windowManager; } // constructor /** * Default constructor. Inits the data on the form. * * @param componentService * service we use to access components */ public EditCompViewModel(@Nonnull ComponentService componentService) { this.setComponentService(componentService); initData(); } /** * Inits the data on the form. */ @NotifyChange({ "componentName", "name", "description", "caption", "postPreviewSize", "sessionTimeout" }) public void initData() { currentComponent = (Component) Executions.getCurrent().getDesktop().getAttribute("componentToEdit"); if (currentComponent.getComponentType().equals(ComponentType.FORUM)) { componentType = "jcommune"; } else { componentType = "antarcticle"; } componentName = valueOf(currentComponent.getName()); name = valueOf(currentComponent.getProperty(componentType + ".name")); description = valueOf(currentComponent.getDescription()); caption = valueOf(currentComponent.getProperty(componentType + ".caption")); postPreviewSize = valueOf(currentComponent.getProperty(componentType + ".postPreviewSize")); sessionTimeout = valueOf(currentComponent.getProperty(componentType + ".session_timeout")); } // service functions /** * Returns all components. * * @return the list of the components */ public List<Component> getComponents() { return componentService.getAll(); } // commands /** * Saves a component. Shows validation messages, if something is wrong */ @Command() @NotifyChange({ "componentName", "name", "description", "caption", "postPreviewSize", "sessionTimeout" }) public void save() { boolean correct = true; validationMessages.clear(); if (checkCorrect()) { currentComponent.setName(componentName); currentComponent.setDescription(description); currentComponent.setProperty(componentType + ".name", name); currentComponent.setProperty(componentType + ".caption", caption); currentComponent.setProperty(componentType + ".postPreviewSize", postPreviewSize); currentComponent.setProperty(componentType + ".session_timeout", sessionTimeout); try { componentService.saveComponent(currentComponent); } catch (ValidationException e) { validationMessages.put("componentName", Labels.getLabel(ITEM_ALREADY_EXISTS)); correct = false; } if (correct) { validationMessages.clear(); Executions.sendRedirect(""); } } } /** * Cancels all the actions */ @Command() @NotifyChange({ "componentName", "name", "description", "caption", "postPreviewSize", "validationMessages", "sessionTimeout" }) public void cancel() { initData(); validationMessages.clear(); Executions.sendRedirect(""); } // helpers /** * Returns string value of the field or empty string if string is null * * @param value * value of the string * @return string value of the field or empty string if string is null */ public String valueOf(String value) { return (value == null) ? "" : value; } /** * Check if input data is correct * * @return true if input is correct, else otherwise */ public boolean checkCorrect() { boolean correct = true; if (name == null || name.equals("")) { validationMessages.put("name", Labels.getLabel(EMPTY_TITLE)); correct = false; } if (componentName == null || componentName.equals("")) { validationMessages.put("componentName", Labels.getLabel(EMPTY_NAME)); correct = false; } return correct; } // getters & setters for web-form /** * Returns the title for current component * * @return name value from web-form */ public String getName() { return name; } /** * Sets the title for the current component * * @param name * value to set */ public void setName(String name) { this.name = name; } /** * Returns the description for the current component * * @return description value from web-form */ public String getDescription() { return description; } /** * Sets the description for the current component * * @param description * to set on web-form */ public void setDescription(String description) { this.description = description; } /** * Returns the name of the current component * * @return component name value from web-form */ public String getComponentName() { return componentName; } /** * Sets the name for current component * * @param componentName * new component name value on web-form */ public void setComponentName(String componentName) { this.componentName = componentName; } /** * Returns validation messages for data input * * @return validation messages */ public Map<String, String> getValidationMessages() { return validationMessages; } // getter and setter for current component we edit /** * Gets the current component we edit * * @return current component */ public Component getCurrentComponent() { return currentComponent; } /** * Sets the current component we edit * * @param currentComponent * - to set */ public void setCurrentComponent(Component currentComponent) { this.currentComponent = currentComponent; } /** * Returns caption from the web-form * * @return caption */ public String getCaption() { return caption; } /** * Sets the current caption * * @param caption * - to set on web-form */ public void setCaption(String caption) { this.caption = caption; } /** * Returns post preview size from the web-form * * @return post preview size */ public String getPostPreviewSize() { return postPreviewSize; } /** * Sets the current component we edit * * @param postPreviewSize * - to set on web-form */ public void setPostPreviewSize(String postPreviewSize) { this.postPreviewSize = postPreviewSize; } /** * Returns session timeout value from the web-form * * @return session timeout */ @NotEmpty(message = "Last name can not be null") public String getSessionTimeout() { return sessionTimeout; } /** * Sets session timeout * * @param sessionTimeout * - to set on web-form */ public void setSessionTimeout(String sessionTimeout) { this.sessionTimeout = sessionTimeout; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1235"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// TODO: Also add information on how to contact you by electronic and paper mail. package com.github.vrpolak.q10sk.reference.implementation.api; /** * Object used for running q10sk programs. * * <p>The behavior corresponds to an immutable object * whose method mutates some of given arguments. * Implementations are free to contain mutable data themselves, * for example various caches. * * @author Vratko Polak */ public interface Q10skRunner { /* * Run program defined by state, calling consumer and producer for output and input repsectively. * * <p>If this returns, the program reached halted state. * * @param state the initial state of the program, never changed * @param consumer the consumer to be called when the program want to output, mutated on call * @param producer the producer to call when the program requires input, mutated on cal */ void run(final Q10skStateTreeRootNode state, final BitConsumer consumer, final BitProducer producer); }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1236"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.eclipse.mylar.zest.core.internal.gefx; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.FigureCanvas; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.gef.DefaultEditDomain; import org.eclipse.gef.EditDomain; import org.eclipse.gef.EditPart; import org.eclipse.gef.MouseWheelHandler; import org.eclipse.gef.MouseWheelZoomHandler; import org.eclipse.gef.ui.parts.ScrollingGraphicalViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.PlatformUI; /** * * @author Ian Bull * @author Chris Callendar */ public abstract class NonThreadedGraphicalViewer extends ScrollingGraphicalViewer { private List revealListeners = null; /** * ThreadedGraphicalViewer constructor. * @param parent The composite that this viewer will be added to. */ public NonThreadedGraphicalViewer(Composite parent) { super(); revealListeners = new ArrayList(1); // create the FigureCanvas createControl(parent); EditDomain ed = new DefaultEditDomain( null ); ed.addViewer( this ); setEditDomain( ed ); hookControl(); getFigureCanvas().setScrollBarVisibility(FigureCanvas.NEVER); getControl().addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { if (!revealListeners.isEmpty()) { // Go through the reveal list and let everyone know that the view // is now available. Remove the listeners so they are only called once! Iterator iterator = revealListeners.iterator(); while (iterator.hasNext() ) { RevealListener reveallisetner = (RevealListener) iterator.next(); reveallisetner.revealed(getControl()); iterator.remove(); } } } }); getControl().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { } }); ((Canvas)getControl()).setBackground( ColorConstants.white ); // Scroll-wheel Zoom setProperty(MouseWheelHandler.KeyGenerator.getKey(SWT.MOD1), MouseWheelZoomHandler.SINGLETON); } /* * (non-Javadoc) * @see org.eclipse.gef.ui.parts.ScrollingGraphicalViewer#reveal(org.eclipse.gef.EditPart) */ public void reveal(EditPart part) { // @tag rootEditPart : Don't reveal root edit parts if (!(part instanceof GraphRootEditPart)) super.reveal(part); } private class MyRunnable implements Runnable{ boolean isVisible; public void run() { isVisible = getControl().isVisible();} } /** * Adds a reveal listener to the view. Note: A reveal listener will * only every be called ONCE!!! even if a view comes and goes. There * is no remove reveal listener. * @param revealListener */ public void addRevealListener( final RevealListener revealListener ) { MyRunnable myRunnable = new MyRunnable(); PlatformUI.getWorkbench().getDisplay().syncExec( myRunnable); if ( myRunnable.isVisible ) revealListener.revealed( (Composite)getControl() ); else revealListeners.add(revealListener); } /** * Does some initializing of the viewer. */ protected abstract void configureGraphicalViewer(); /** * Sets the contents of the viewer and configures the graphical viewer. * @param model */ public void setContents(Object model) { this.configureGraphicalViewer(); super.setContents(model); //@tag zest.experimental.contents : publish a property change that the model has changed. This will allow linked viewers to update. setProperty(IZestViewerProperties.GRAPH_VIEWER_CONTENTS, model); } /** * Updates the contents <b>without</b> configuring the graphical viewer. * Only call this if the graphical viewer has already be configured. * @param model */ public void updateContents(Object model) { super.setContents(model); //@tag zest.experimental.contents : publish a property change that the model has changed. This will allow linked viewers to update. setProperty(IZestViewerProperties.GRAPH_VIEWER_CONTENTS, model); } /** * Gets the absolute size of the canvas. * @return Dimension in absolute coords */ public Dimension getCanvasSize() { Dimension dim = new Dimension(getFigureCanvas().getSize()); dim.shrink(getFigureCanvas().getBorderWidth(), getFigureCanvas().getBorderWidth()); return dim; } /** * Gets the translated size of the canvas. * @return Dimension relative */ public Dimension getTranslatedCanvasSize() { Dimension dim = getCanvasSize(); //mainCanvas.getViewport().translateToRelative(dim); return dim; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1237"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.sagebionetworks.change.workers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Date; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.sagebionetworks.StackConfiguration; import org.sagebionetworks.common.util.progress.ProgressCallback; import org.sagebionetworks.repo.manager.EntityManager; import org.sagebionetworks.repo.manager.EntityPermissionsManager; import org.sagebionetworks.repo.model.AccessControlList; import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL; import org.sagebionetworks.repo.model.Folder; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.UserInfo; import org.sagebionetworks.repo.model.jdo.KeyFactory; import org.sagebionetworks.repo.model.table.EntityDTO; import org.sagebionetworks.repo.model.util.AccessControlListUtil; import org.sagebionetworks.table.cluster.ConnectionFactory; import org.sagebionetworks.table.cluster.TableIndexDAO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.google.common.collect.Lists; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:test-context.xml" }) public class EntityHierarchyChangeWorkerIntegrationTest { private static final int MAX_WAIT_MS = 30*1000; @Autowired StackConfiguration config; @Autowired EntityManager entityManager; @Autowired ConnectionFactory tableConnectionFactory; @Autowired EntityPermissionsManager entityPermissionsManager; TableIndexDAO indexDao; @Mock ProgressCallback mockProgressCallback; UserInfo adminUser; Long userId; Project project; Folder folder; Folder child; @Before public void before(){ // Only run this test if the table feature is enabled. Assume.assumeTrue(config.getTableEnabled()); // this is still an integration test even though a mock progress is used. MockitoAnnotations.initMocks(this); userId = BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId(); adminUser = new UserInfo(true, userId); indexDao = tableConnectionFactory.getAllConnections().get(0); project = new Project(); project.setName("parent"); String id = entityManager.createEntity(adminUser, project, null); project = entityManager.getEntity(adminUser, id, Project.class); // create a folder folder = new Folder(); folder.setName("folder"); folder.setParentId(project.getId()); id = entityManager.createEntity(adminUser, folder, null); folder = entityManager.getEntity(adminUser, id, Folder.class); // create a child child = new Folder(); child.setName("child"); child.setParentId(folder.getId()); id = entityManager.createEntity(adminUser, child, null); child = entityManager.getEntity(adminUser, id, Folder.class); } @After public void after(){ if(project != null){ entityManager.deleteEntity(adminUser, project.getId()); } } @Test public void testRoundTrip() throws InterruptedException{ // wait for the child to be replicated EntityDTO replicatedChild = waitForEntityDto(child.getId()); assertNotNull(replicatedChild); assertEquals(KeyFactory.stringToKey(project.getId()), replicatedChild.getBenefactorId()); // Delete the replicated data indexDao.deleteEntityData(mockProgressCallback , Lists.newArrayList(KeyFactory.stringToKey(child.getId()))); // Add an ACL to the folder to trigger a hierarchy change AccessControlList acl = AccessControlListUtil.createACLToGrantEntityAdminAccess(folder.getId(), adminUser, new Date()); entityPermissionsManager.overrideInheritance(acl, adminUser); // the update should trigger the replication of the child replicatedChild = waitForEntityDto(child.getId()); assertNotNull(replicatedChild); // the benefactor should now the folder. assertEquals(KeyFactory.stringToKey(folder.getId()), replicatedChild.getBenefactorId()); } /** * Helper to wait for replicated data to appear. * @param entityId * @return * @throws InterruptedException */ public EntityDTO waitForEntityDto(String entityId) throws InterruptedException{ long startTimeMS = System.currentTimeMillis(); while(true){ EntityDTO entityDto = indexDao.getEntityData(KeyFactory.stringToKey(entityId)); if(entityDto != null){ return entityDto; } System.out.println("Waiting for entity data to be replicated for id: "+entityId); Thread.sleep(2000); assertTrue("Timed-out waiting for entity data to be replicated.",System.currentTimeMillis()-startTimeMS < MAX_WAIT_MS); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1238"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.tuxdevelop.spring.data.solr.demo.repository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; import org.springframework.data.solr.core.query.result.*; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.tuxdevelop.spring.data.solr.demo.configuration.ITConfiguration; import org.tuxdevelop.spring.data.solr.demo.domain.Store; import org.tuxdevelop.spring.data.solr.demo.util.SolrInitializer; import java.util.Collection; import java.util.LinkedList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = ITConfiguration.class) public class StoreRepositoryIT { @Autowired private StoreRepository storeRepository; @Autowired private SolrInitializer solrInitializer; /* * init solr */ @Before public void init() throws Exception { solrInitializer.importStarbucks(); } /* * Search IT */ @Test public void findByNameIT() { final String nameToFind = "Steaming Kettle"; final Collection<Store> stores = storeRepository.findByName(nameToFind); assertThat(stores).isNotEmpty(); assertThat(stores).hasSize(1); } @Test public void findByNameQueryIT() { final String nameToFind = "Steaming Kettle"; final Collection<Store> stores = storeRepository.findByNameQuery(nameToFind); assertThat(stores).isNotEmpty(); assertThat(stores).hasSize(1); } @Test public void findByNameFilterQueryIT() { final String nameToFind = "Steaming Kettle"; final Collection<Store> stores = storeRepository.findByNameFilterQuery(nameToFind); assertThat(stores).isNotEmpty(); assertThat(stores).hasSize(1); } @Test public void findStoreByNameFilterQueryIT() { final String nameToFind = "Steaming Kettle"; final Collection<Store> stores = storeRepository.findStoreByNameFilterQuery(nameToFind); assertThat(stores).isNotEmpty(); assertThat(stores).hasSize(1); } @Test public void findByLocationNearIT() { final Point point = new Point(43, -71); final Distance distance = new Distance(10); final Collection<Store> stores = storeRepository.findByLocationNear(point, distance); assertThat(stores).isNotEmpty(); assertThat(stores).hasSize(2); for (Store store : stores) { System.out.println(store); } } @Test public void findByProductsInIT() { final Collection<String> products = new LinkedList<>(); products.add("Lunch"); products.add("Oven-warmed Food"); products.add("Reserve Amenity"); final Collection<Store> stores = storeRepository.findByProductsIn(products); assertThat(stores).isNotEmpty(); System.out.println("Size: " + stores.size()); } @Test public void findByPoductsInAndLocationNearIT() { final Collection<String> products = new LinkedList<>(); products.add("Lunch"); products.add("Oven-warmed Food"); products.add("Reserve Amenity"); final Point point = new Point(43, -71); final Distance distance = new Distance(10); final Collection<Store> stores = storeRepository.findByProductsInAndLocationNear(products, point, distance); assertThat(stores).hasSize(1); } /* * Solr Operations IT */ @Test public void updateProductsIT() { final String newProduct = "1&1 Handy Flat!"; final String id = "1"; final Store store = storeRepository.findOne(id); assertThat(store).isNotNull(); final Collection<String> products = store.getProducts(); final Collection<String> newProducts = new LinkedList<>(); newProducts.add(newProduct); storeRepository.updateProducts(id, newProducts); final Store updatedStore = storeRepository.findOne(id); assertThat(updatedStore).isNotNull(); final Collection<String> updatedProducts = updatedStore.getProducts(); assertThat(products).isNotEqualTo(updatedProducts); assertThat(updatedProducts).contains(newProduct); } /* * Facetting */ @Test public void findByZipCodeFacetOnProductsIT() { final String zipCode = "03833-2105"; final FacetPage<Store> response = storeRepository.findByZipCodeFacetOnProducts(zipCode, new PageRequest(0, 20)); assertThat(response).isNotNull(); assertThat(response.getContent()).isNotEmpty(); assertThat(response.getContent()).hasSize(3); for (final Store store : response.getContent()) { System.err.println(store); } Page<FacetFieldEntry> page = response.getFacetResultPage("products"); final int size = page.getSize(); System.err.println("size:" + size); final Page<FacetFieldEntry> facetResultPage = response.getFacetResultPage("products"); List<FacetFieldEntry> content = facetResultPage.getContent(); System.err.println("content.size:" + content.size()); for (final FacetFieldEntry facetFieldEntry : content) { System.err.println("Found: " + facetFieldEntry.getValue()); } } @Test public void findFacetOnNameIT() { final List<String> products = new LinkedList<>(); products.add("Lunch"); final FacetPage<Store> response = storeRepository.findFacetOnName(products, new PageRequest(0, 20)); assertThat(response).isNotNull(); assertThat(response.getContent()).isNotEmpty(); for (final Store store : response.getContent()) { System.err.println(store); } final Page<FacetFieldEntry> page = response.getFacetResultPage("name"); final int size = page.getSize(); System.err.println("size:" + size); final Page<FacetFieldEntry> facetResultPage = response.getFacetResultPage("name"); List<FacetFieldEntry> content = facetResultPage.getContent(); System.err.println("content.size:" + content.size()); for (final FacetFieldEntry facetFieldEntry : content) { System.err.println("Found: " + facetFieldEntry.getValue()); } } @Test public void findFacetOnNameSolrTemplateIT() { final List<String> products = new LinkedList<>(); products.add("Lunch"); final FacetPage<Store> response = storeRepository.findFacetOnNameSolrTemplate(products); assertThat(response).isNotNull(); assertThat(response.getContent()).isNotEmpty(); for (final Store store : response.getContent()) { System.err.println(store); } final Page<FacetFieldEntry> page = response.getFacetResultPage("name"); final int size = page.getSize(); System.err.println("size:" + size); final Page<FacetFieldEntry> facetResultPage = response.getFacetResultPage("name"); List<FacetFieldEntry> content = facetResultPage.getContent(); System.err.println("content.size:" + content.size()); for (final FacetFieldEntry facetFieldEntry : content) { System.err.println("Found: " + facetFieldEntry.getValue()); } } @Test public void findByFacetOnProductsIT() { final FacetPage<Store> response = storeRepository.findByFacetOnProducts(new PageRequest(0, 100)); assertThat(response).isNotNull(); assertThat(response.getContent()).isNotEmpty(); assertThat(response.getContent()).hasSize(100); for (final Store store : response.getContent()) { System.err.println(store); } final Page<FacetFieldEntry> page = response.getFacetResultPage("products"); final int size = page.getSize(); System.err.println("size:" + size); final Page<FacetFieldEntry> facetResultPage = response.getFacetResultPage("products"); List<FacetFieldEntry> content = facetResultPage.getContent(); System.err.println("content.size:" + content.size()); for (final FacetFieldEntry facetFieldEntry : content) { System.err.println("Found: " + facetFieldEntry.getValue()); } } /* * Grouping */ @Test public void groupByZipCodeIT() { final String lunch = "Lunch"; final List<String> products = new LinkedList<>(); products.add(lunch); final GroupPage<Store> response = storeRepository.groupByZipCode(products); System.err.println(" GroupResult<Store> groupResult = response.getGroupResult("zipCode"); final Page<GroupEntry<Store>> groupEntries = groupResult.getGroupEntries(); for (final GroupEntry<Store> groupEntry : groupEntries) { final String groupValue = groupEntry.getGroupValue(); System.err.println("groupValue: " + groupValue); final List<Store> groupContet = groupEntry.getResult().getContent(); System.err.println("Members of the group: "); for (final Store store : groupContet) { System.err.println(store); } } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1239"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.wyona.yanel.impl.resources; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.api.attributes.CreatableV2; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.navigation.Node; import org.wyona.yanel.core.navigation.Sitetree; import org.wyona.yanel.core.serialization.SerializerFactory; import org.wyona.yanel.core.source.ResourceResolver; import org.wyona.yanel.core.transformation.I18nTransformer2; import org.wyona.yanel.core.transformation.XIncludeTransformer; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.apache.log4j.Category; import org.apache.xml.resolver.tools.CatalogResolver; import org.apache.xml.serializer.Serializer; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamSource; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationUtil; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; public class ResourceCreatorResource extends Resource implements ViewableV2{ private static Category log = Category.getInstance(ResourceCreatorResource.class); private boolean ajaxBrowser = false; public ResourceCreatorResource() { } public boolean exists() { return true; } public long getSize() { return -1; } public String getMimeType(String viewId) { if (viewId != null && viewId.equals("source")) return "application/xml"; return "application/xhtml+xml"; } public View getView(String viewId) { if(request.getHeader("User-Agent").indexOf("rv:1.7") < 0) { ajaxBrowser = true; } View view = new View(); String mimeType = getMimeType(viewId); view.setMimeType(mimeType); try { org.wyona.yarep.core.Repository repo = getRealm().getRepository(); if (viewId != null && viewId.equals("source")) { view.setInputStream(new java.io.StringBufferInputStream(getScreen())); view.setMimeType("application/xml"); return view; } String[] xsltPath = getXSLTPath(getPath()); if (xsltPath != null) { // create reader: XMLReader xmlReader = XMLReaderFactory.createXMLReader(); CatalogResolver catalogResolver = new CatalogResolver(); xmlReader.setEntityResolver(catalogResolver); // create xslt transformer: SAXTransformerFactory tf = (SAXTransformerFactory)TransformerFactory.newInstance(); TransformerHandler[] xsltHandlers = new TransformerHandler[xsltPath.length]; for (int i = 0; i < xsltPath.length; i++) { xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(repo.getNode(xsltPath[i]).getInputStream())); xsltHandlers[i].getTransformer().setParameter("yanel.path.name", PathUtil.getName(getPath())); xsltHandlers[i].getTransformer().setParameter("yanel.path", getPath()); xsltHandlers[i].getTransformer().setParameter("yanel.back2context", PathUtil.backToContext(realm, getPath())); xsltHandlers[i].getTransformer().setParameter("yarep.back2realm", PathUtil.backToRealm(getPath())); xsltHandlers[i].getTransformer().setParameter("language", getRequestedLanguage()); } // create i18n transformer: I18nTransformer2 i18nTransformer = new I18nTransformer2("global", getRequestedLanguage(), getRealm().getDefaultLanguage()); i18nTransformer.setEntityResolver(catalogResolver); // create xinclude transformer: XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(); ResourceResolver resolver = new ResourceResolver(this); xIncludeTransformer.setResolver(resolver); // create serializer: Serializer serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // chain everything together (create a pipeline): xmlReader.setContentHandler(xsltHandlers[0]); for (int i=0; i<xsltHandlers.length-1; i++) { xsltHandlers[i].setResult(new SAXResult(xsltHandlers[i+1])); } xsltHandlers[xsltHandlers.length-1].setResult(new SAXResult(xIncludeTransformer)); xIncludeTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(baos); // execute pipeline: xmlReader.parse(new InputSource(new java.io.StringBufferInputStream(getScreen()))); // write result into view: view.setInputStream(new ByteArrayInputStream(baos.toByteArray())); return view; } else { log.debug("Mime-Type: " + mimeType); view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } } catch(Exception e) { log.error(e + " (" + getPath() + ", " + getRealm() + ")", e); } view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } public ViewDescriptor[] getViewDescriptors() { ViewDescriptor[] vd = new ViewDescriptor[2]; vd[0] = new ViewDescriptor("default"); vd[0].setMimeType(getMimeType(null)); vd[1] = new ViewDescriptor("source"); vd[1].setMimeType(getMimeType("source")); return vd; } /** * Flow */ private String getScreen() { StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http: sb.append("<head><title>create resource</title>"); sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PathUtil.getResourcesHtdocsPath(this) + "css/resource-creator.css\"/>"); sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-css/progressBar.css\"/>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/prototype.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/progressBar.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/sorttable.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPath(this)+ "js/ajaxlookup.js\" type=\"text/javascript\"></script>"); sb.append("</head>"); sb.append("<body>"); HttpServletRequest request = getRequest(); Enumeration parameters = request.getParameterNames(); if (!parameters.hasMoreElements()) { getSelectResourceTypeScreen(sb); } else { if (request.getParameter("save-as") != null) { // NOTE: Save as has been merged with getResourceScreen because otherwise uploading of data would be rather cumbersome. //getSaveAsScreen(sb); getNoSuchScreen(sb); } else if (request.getParameter("save") != null) { getSaveScreen(sb); } else if (request.getParameter("lookup") != null) { return getLookUp().toString(); } else if (request.getParameter("resource-type") != null) { getResourceScreen(sb); } else { log.info("Fallback ..."); //getNoSuchScreen(sb); getSelectResourceTypeScreen(sb); } } sb.append("</body>"); sb.append("</html>"); return sb.toString(); } private void getSelectResourceTypeScreen(StringBuffer sb) { sb.append("<h4>Create new page (step 0)</h4>"); sb.append("<h2>Select template (resp. resource type)</h2>"); sb.append("<form>"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); ResourceTypeDefinition[] rtds = getResourceTypeDefinitions(); if (rtds != null) { sb.append("Template (resp. resource type): <select name=\"resource-type\">"); for (int i = 0; i < rtds.length; i++) { try { Resource resource = rtr.newResource(rtds[i].getResourceTypeUniversalName()); if (resource != null && ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) { sb.append("<option value=\"" + rtds[i].getResourceTypeNamespace() + "::" + rtds[i].getResourceTypeLocalName() + "\">" + getDisplayName(rtds[i].getResourceTypeLocalName(), rtds[i].getResourceTypeNamespace()) + "</option>"); } else { log.warn("Resource type: " + rtds[i] + " does not implement CreatableV2 interface!"); } } catch(Exception e) { log.error(e); } } sb.append("</select>"); } else { sb.append("<p>No resource types!</p>"); } sb.append("<br/><input type=\"button\" name=\"Cancel\" value=\"Cancel\" onclick=\"location.href='" + getReferer() + "'\"/>"); sb.append("<input type=\"hidden\" name=\"referer\" value=\"" + getReferer() + "\"/>"); sb.append("<input type=\"submit\" value=\"Next\"/>"); sb.append("</form>"); } private void getNoSuchScreen(StringBuffer sb) { sb.append("<p>No such screen!</p>"); } /** * Save screen */ private void getSaveScreen(StringBuffer sb) { sb.append("<h4>Create new page (step 2)</h4>"); Path pathOfNewResource = null; try { pathOfNewResource = create(); } catch(Exception e) { log.warn(e.getMessage(), e); sb.append("<p>Exception: "+e.getMessage()+"</p>"); sb.append("<a href=\"javascript:history.back()\">back</a>"); return; } sb.append("<h2>Resource has been created</h2>"); HttpServletRequest request = getRequest(); Enumeration parameters = request.getParameterNames(); if (parameters.hasMoreElements()) { sb.append("<ul>"); while (parameters.hasMoreElements()) { String parameter = (String) parameters.nextElement(); if (parameter.indexOf("rp.") == 0) { sb.append("<li>"+parameter+": "+request.getParameter(parameter)+"</li>"); } } sb.append("</ul>"); } if (log.isDebugEnabled()) log.debug("New Resource: " + PathUtil.backToRealm(getPath()) + ", " + pathOfNewResource); // NOTE: Back to realm has the form of ./ or ../ or ../../ etc., hence drop the leading slash! if (pathOfNewResource != null) { String href = PathUtil.backToRealm(getPath()) + pathOfNewResource.toString().substring(1); sb.append("<p>New resource can be accessed at: <a href=\"" + href + "\">" + href + "</a></p>"); } else { sb.append("<p>Please note that no path/URL has been associated with the newly created resource, because it might be some internally used resource.</p>"); } } private void getResourceScreen(StringBuffer sb) { String rtps = getRequest().getParameter("resource-type"); String resNamespace = rtps.substring(0, rtps.indexOf("::")); String resName = rtps.substring(rtps.indexOf("::") + 2); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); if (getRequest().getParameter("create-new-folder") != null && !getRequest().getParameter("create-new-folder").equals("")) { try { create(getRequest().getParameter("create-new-folder"), getRequest().getParameter("lookin"), "http: } catch (Exception e) { sb.append("<p>Could not create folder. Exception: " + e + "</p>"); log.error(e.getMessage(), e); } } try { String universalName = "<{"+ resNamespace +"}"+ resName +"/>"; log.debug("Universal Name: " + universalName); Resource resource = rtr.newResource(universalName); if (resource != null) { if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) { sb.append("<h4>Create new page (step 1)</h4>"); sb.append("<h2>Enter/Select template (resp. resource) specific parameters and \"Save As\"</h2>"); sb.append("<form enctype=\"multipart/form-data\" method=\"post\">"); sb.append("<p>Template (resp. resource type): " + resName + " ("+resNamespace+")</p>"); // TODO: Add this parameter to the continuation within the session! sb.append("<input type=\"hidden\" name=\"resource-type\" value=\"" + rtps + "\"/>"); Property[] defaultProperties = getDefaultProperties(resName, resNamespace); String[] propertyNames = ((CreatableV2) resource).getPropertyNames(); if ((propertyNames != null && propertyNames.length > 0) || defaultProperties != null) { sb.append("<p>Resource specific properties:</p>"); } else { sb.append("<p>No resource specific properties!</p>"); } if (propertyNames != null && propertyNames.length > 0) { sb.append("<table border=\"1\">"); for (int i = 0; i < propertyNames.length; i++) { sb.append("<tr><td>" + propertyNames[i] + ":&#160;&#160;&#160;</td><td>"); String propertyType = ((CreatableV2) resource).getPropertyType(propertyNames[i]); if (propertyType != null && propertyType.equals(CreatableV2.TYPE_UPLOAD)) { sb.append("<input type=\"file\" name=\"rp." + propertyNames[i] + "\"/><br/>"); } else if (propertyType != null && propertyType.equals(CreatableV2.TYPE_SELECT)) { Object defaultValues = ((CreatableV2) resource).getProperty(propertyNames[i]); if (defaultValues instanceof java.util.HashMap) { sb.append("<select name=\"rp." + propertyNames[i] + "\">"); sb.append(" <option value=\"*\">*</option>"); sb.append(" <option value=\"public\">public</option>"); sb.append(" <option value=\"private\">private</option>"); sb.append("</select><br/>"); } else { sb.append("Exception: Parameter doesn't seem to be a of type SELECT: " + propertyNames[i]); } } else if (propertyType != null && propertyType.equals(CreatableV2.TYPE_PASSWORD)) { //sb.append("<input type=\"file\" name=\"rp." + propertyNames[i] + "\"/><br/>"); Object value = ((CreatableV2) resource).getProperty(propertyNames[i]); if (value == null) { sb.append("<input type=\"password\" name=\"rp." + propertyNames[i] + "\" value=\"\" size=\"60\"/><br/>"); } else { sb.append("<input type=\"password\" name=\"rp." + propertyNames[i] + "\" value=\"" + value + "\" size=\"60\"/><br/>"); } } else { log.debug("Let's assume the property is of type text ..."); Object value = ((CreatableV2) resource).getProperty(propertyNames[i]); if (value == null) { sb.append("<input type=\"text\" name=\"rp." + propertyNames[i] + "\" value=\"\" size=\"60\"/><br/>"); } else { sb.append("<input type=\"text\" name=\"rp." + propertyNames[i] + "\" value=\"" + value + "\" size=\"60\"/><br/>"); } } sb.append("</td></tr>"); } sb.append("</table>"); } if (defaultProperties != null) { sb.append("<ul>"); for (int i = 0; i < defaultProperties.length; i++) { sb.append("<li>"); sb.append("Default property: " + defaultProperties[i]); sb.append("<input type=\"hidden\" name=\"rp." + defaultProperties[i].getName() + "\" value=\"" + defaultProperties[i].getValue() + "\"/>"); sb.append("</li>"); } sb.append("</ul>"); } sb.append("<br/><br/>"); sb.append("<div class=\"creatorFileBrowser\">"); sb.append("<table>"); sb.append("<tr><td colspan=\"2\" class=\"fileBrowserHead\">Save as:</td></tr>"); sb.append("<tr><td colspan=\"2\">"); sb.append("<div id=\"lookup\">"); sb.append(getLookUp()); sb.append("</div>"); sb.append("</td></tr>"); sb.append("<tr><td colspan=\"2\" class=\"fileBrowserNewName\">"); String createName = getRequest().getParameter("create-name"); if (createName != null) { sb.append("New name: <input type=\"text\" name=\"create-name\" value=\"" + createName + "\"/>"); } else { sb.append("New name: <input type=\"text\" name=\"create-name\"/>"); } sb.append("</td></tr>"); sb.append("<tr>"); sb.append("<td>"); sb.append("<input type=\"button\" name=\"Cancel\" value=\"Cancel\" onclick=\"location.href='" + getReferer() + "'\"/>"); sb.append("<input type=\"hidden\" name=\"referer\" value=\"" + getReferer() + "\"/>"); sb.append("</td>"); sb.append("<td align=\"right\">"); sb.append("<input type=\"submit\" value=\"Save new resource\" name=\"save\"/>"); sb.append("</td>"); sb.append("</tr>"); sb.append("</table>"); sb.append("</div>"); sb.append("</form>"); // TODO: Display realm navigation (sitetree, topic map, ...) resp. introduce another step } } } catch (Exception e) { sb.append("<p>Exception: " + e + "</p>"); log.error(e.getMessage(), e); } } /** * Creates new resource * @return Path of new resource */ private Path create() throws Exception { return create(getRequest().getParameter("create-name"), getRequest().getParameter("lookin"), getRequest().getParameter("resource-type")); } /** * Creates new resource * @param String createName * @param String lookinPath * @param String resourceType * @return Path of new resource */ private Path create(String createName, String lookinPath, String resourceType) throws Exception { org.wyona.yanel.core.map.Realm realm = getRealm(); Path pathOfResourceCreator = new Path(getPath()); org.wyona.commons.io.Path parent = new org.wyona.commons.io.Path(pathOfResourceCreator.toString()).getParent(); Path pathOfNewResource = new Path(getParentOfNewResource(parent, lookinPath).toString() + createName); if (log.isDebugEnabled()) log.debug("Path of new resource: " + pathOfNewResource); pathOfNewResource = new Path(removeTooManySlashes(pathOfNewResource.toString())); if (log.isDebugEnabled()) log.debug("Path of new resource without too many slashes: " + pathOfNewResource); String rtps = resourceType; String resNamespace = rtps.substring(0, rtps.indexOf("::")); String resName = rtps.substring(rtps.indexOf("::") + 2); Resource newResource = yanel.getResourceManager().getResource(getEnvironment(), realm, pathOfNewResource.toString(), new ResourceConfiguration(resName, resNamespace, null)); if (newResource != null) { if (ResourceAttributeHelper.hasAttributeImplemented(newResource, "Creatable", "2")) { createName = ((CreatableV2) newResource).getCreateName(createName); if (createName != null && createName.equals("")) { throw new Exception("Please enter a name!"); } if (createName == null) { pathOfNewResource = null; newResource.setPath(null); } else { pathOfNewResource = new Path(removeTooManySlashes(getParentOfNewResource(parent, lookinPath).toString()) + createName); newResource.setPath(pathOfNewResource.toString()); } ((CreatableV2) newResource).create(request); if (pathOfNewResource != null) { createResourceConfiguration(newResource); } } else { throw new Exception("creation NOT successfull!"); } } else { throw new Exception("creation NOT successful (newResource == null)!"); } return pathOfNewResource; } /** * Create resource configuration (yanel-rc) */ private void createResourceConfiguration(Resource newResource) throws Exception { StringBuffer rcContent = new StringBuffer("<?xml version=\"1.0\"?>\n\n"); rcContent.append("<yanel:resource-config xmlns:yanel=\"http: rcContent.append("<yanel:rti name=\"" + newResource.getRTD().getResourceTypeLocalName() + "\" namespace=\"" + newResource.getRTD().getResourceTypeNamespace() + "\"/>\n\n"); java.util.HashMap rtiProperties = ((CreatableV2) newResource).createRTIProperties(request); if (rtiProperties != null) { if (log.isDebugEnabled()) log.debug(rtiProperties + " " + PathUtil.getRTIPath(newResource.getPath())); java.util.Iterator iterator = rtiProperties.keySet().iterator(); while (iterator.hasNext()) { String property = (String) iterator.next(); String value = (String) rtiProperties.get(property); if (value != null) { rcContent.append("<yanel:property name=\"" + property + "\" value=\"" + value + "\"/>\n"); if(log.isDebugEnabled()) log.debug("Set Property: " + property + ", " + value); } else { log.warn("Property value is null: " + property); } } } else { log.warn("No RTI properties: " + newResource.getPath()); } rcContent.append("</yanel:resource-config>"); org.wyona.yarep.core.Repository rcRepo = newResource.getRealm().getRTIRepository(); org.wyona.commons.io.Path newRCPath = new org.wyona.commons.io.Path(PathUtil.getRCPath(newResource.getPath())); if (log.isDebugEnabled()) log.debug(newRCPath); org.wyona.yanel.core.util.YarepUtil.addNodes(rcRepo, newRCPath.toString(), org.wyona.yarep.core.NodeType.RESOURCE); java.io.Writer writer = new java.io.OutputStreamWriter(rcRepo.getNode(newRCPath.toString()).getOutputStream()); writer.write(rcContent.toString()); writer.close(); } /** * Get resource type definitions */ private ResourceTypeDefinition[] getResourceTypeDefinitions() { ResourceTypeRegistry rtr = new ResourceTypeRegistry(); ResourceConfiguration rc = getConfiguration(); Document customConfigDoc = rc.getCustomConfiguration(); if (customConfigDoc != null) { Configuration config = ConfigurationUtil.toConfiguration(customConfigDoc.getDocumentElement()); Configuration resourceTypesConfig = config.getChild("resource-types", false); if (resourceTypesConfig != null) { Configuration[] resourceTypeConfigs = resourceTypesConfig.getChildren("resource-type"); if (resourceTypeConfigs.length == 0) return null; ResourceTypeDefinition[] rtds = new ResourceTypeDefinition[resourceTypeConfigs.length]; for (int i = 0; i < resourceTypeConfigs.length; i++) { try { String universalName = "<{"+resourceTypeConfigs[i].getAttribute("namespace")+"}"+resourceTypeConfigs[i].getAttribute("name")+"/>"; rtds[i] = rtr.getResourceTypeDefinition(universalName); log.debug("Resource Type: " + universalName); } catch (Exception e) { log.error(e.getMessage(), e); return null; } } return rtds; } } ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); return rtds; } /** * Get default properties from custom configuration */ private Property[] getDefaultProperties(String resName, String resNamespace) { Document customConfigDoc = getConfiguration().getCustomConfiguration(); if (customConfigDoc != null) { Configuration config = ConfigurationUtil.toConfiguration(customConfigDoc.getDocumentElement()); Configuration resourceTypesConfig = config.getChild("resource-types", false); if (resourceTypesConfig != null) { Configuration[] resourceTypeConfigs = resourceTypesConfig.getChildren("resource-type"); if (resourceTypeConfigs.length == 0) return null; for (int i = 0; i < resourceTypeConfigs.length; i++) { try { if (resourceTypeConfigs[i].getAttribute("namespace").equals(resNamespace) && resourceTypeConfigs[i].getAttribute("name").equals(resName)) { log.debug("Resource Type Found: " + resName + ", " + resNamespace); Configuration[] propertyConfigs = resourceTypeConfigs[i].getChildren("property"); Property[] props = new Property[propertyConfigs.length]; for (int k = 0; k < propertyConfigs.length; k++) { props[k] = new Property(propertyConfigs[k].getAttribute("name"), propertyConfigs[k].getAttribute("value")); log.debug("Property: " + props[k]); } return props; } } catch (Exception e) { log.error(e.getMessage(), e); return null; } } } } return null; } /** * Get the display name from custom configuration */ private String getDisplayName(String resName, String resNamespace) { Document customConfigDoc = getConfiguration().getCustomConfiguration(); if (customConfigDoc != null) { try { org.jdom.Document jdomDocument = new org.jdom.input.DOMBuilder().build(customConfigDoc); org.jdom.xpath.XPath xpath = org.jdom.xpath.XPath.newInstance("/yanel:custom-config/rc:resource-types/rc:resource-type[@name='" + resName + "']/rc:display-name"); xpath.addNamespace("yanel", "http: xpath.addNamespace("rc", "http: org.jdom.Element displayNameElement = (org.jdom.Element) xpath.selectSingleNode(jdomDocument); if (displayNameElement != null) { // TODO: It seems like document does not contain text nodes ... if (log.isDebugEnabled()) log.debug("Display name: " + displayNameElement + " :: " + displayNameElement.getText() + " :: " + displayNameElement.getName()); return displayNameElement.getText(); } else { log.warn("No display name: " + resName); return resName; } } catch (Exception e) { log.error(e.getMessage(), e); return resName; } } return resName; } /** * Return sitetree */ private StringBuffer getLookUp() { StringBuffer sb = new StringBuffer(""); //Sitetree sitetree = (Sitetree) getYanel().getBeanFactory().getBean("repo-navigation"); Sitetree sitetree = getRealm().getRepoNavigation(); Node node = null; String lookinPath = getRequest().getParameter("lookin"); if (lookinPath != null) { node = sitetree.getNode(getRealm(), lookinPath); } else { node = sitetree.getNode(getRealm(), getPath()); } if (node != null) { if (node.isCollection()) { if(log.isDebugEnabled()) log.debug("Is Collection: " + node.getName()); } else if (node.isResource()) { if (log.isDebugEnabled()) log.debug("Is Resource: " + node.getName()); node = node.getParent(); } else { log.error("Neither collection nor resource: " + getPath()); } } else { log.error("No such path '" + getPath() + "' within sitetree! Root node will be used."); node = sitetree.getNode(getRealm(), "/"); } String rtps = getRequest().getParameter("resource-type"); String resNamespace = rtps.substring(0, rtps.indexOf("::")); String resName = rtps.substring(rtps.indexOf("::") + 2); sb.append("<table id=\"resourceCreatorSaveAsTable\">"); sb.append("<tr><td>Look in: " + node.getPath() + "&#160;&#160;&#160;</td><td>New folder: <input type=\"text\" name=\"create-new-folder\"/>&#160;<input type=\"image\" src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/folder-new.png\" alt=\"make a new folder\"/> "); String parent = "/"; if (!node.getPath().equals("/")) { parent = new org.wyona.commons.io.Path(node.getPath()).getParent().toString(); } if (log.isDebugEnabled()) log.debug("Parent: " + parent); if (ajaxBrowser) { sb.append("<a href=\"JavaScript:ajaxlookup('" + resNamespace + "::" + resName + "', '" + parent + "')\"><img src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/go-up.png\" alt=\"go up\" border=\"0\"/></a>"); } else { sb.append("<a href=\"?lookin=" + parent + "&amp;resource-type=" + resNamespace + "::" + resName + "\"><img src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/go-up.png\" alt=\"go up\" border=\"0\"/></a>"); } sb.append("</td></tr>"); sb.append("<tr><td colspan=\"2\">"); sb.append("<div id=\"lookupfiles\">"); sb.append("<table id=\"lookupfilesTable\" class=\"sortable\">"); sb.append("<thead>"); sb.append("<tr><th>Type</th><th>Name</th><th>Resource Type</th></tr>"); sb.append("</thead>"); sb.append("<tbody>"); Node[] children = node.getChildren(); for (int i = 0; i < children.length; i++) { String resourceTypeName; try { resourceTypeName = yanel.getResourceManager().getResource(getEnvironment(), realm, children[i].getPath()).getResourceTypeLocalName(); } catch (Exception e) { log.error(e.getMessage(), e); resourceTypeName = "?"; } if (children[i].isCollection()) { // TODO: Also append resource specific parameters (AJAX ...) if (ajaxBrowser) { sb.append("<tr><td sorttable_customkey=\"Collection\"><a href=\"JavaScript:ajaxlookup('" + resNamespace + "::" + resName + "', '" + node.getPath() + children[i].getName() + "/')\"><img class=\"lookupicon\" src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/folder.png\" alt=\"Collection:\"/></a></td><td><a href=\"JavaScript:ajaxlookup('" + resNamespace + "::" + resName + "', '" + node.getPath() + children[i].getName() + "/')\">" + children[i].getName() + "</a></td><td>" + resourceTypeName + "</td></tr>"); } else { sb.append("<tr><td sorttable_customkey=\"Collection\"><a href=\"?lookin=" + node.getPath() + children[i].getName() + "/&amp;resource-type=" + resNamespace + "::" + resName + "\"><img class=\"lookupicon\" src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/folder.png\" alt=\"Collection:\"/></a></td><td><a href=\"?lookin=" + node.getPath() + children[i].getName() + "/&amp;resource-type=" + resNamespace + "::" + resName + "\">" + children[i].getName() + "</a></td><td>" + resourceTypeName + "</td></tr>"); } } else if (children[i].isResource()) { sb.append("<tr><td sorttable_customkey=\"Resource\"><img class=\"lookupicon\" src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/text-x-generic.png\" alt=\"Resource:\"/></td><td>"+children[i].getName()+"</td><td>" + resourceTypeName + "</td></tr>"); } else { sb.append("<tr><td>?</td><td>"+children[i].getName()+"</td><td>-</td></tr>"); } } sb.append("</tbody>"); sb.append("</table>"); sb.append("<input type=\"hidden\" name=\"lookin\" value=\"" + node.getPath() + "\"/>"); sb.append("</div>"); sb.append("</td></tr>"); sb.append("</table>"); return sb; } /** * Get XSLT path */ private String[] getXSLTPath(String path) throws Exception { String[] xsltPath = getResourceConfigProperties("xslt"); if (xsltPath != null && xsltPath.length > 0) return xsltPath; log.info("No XSLT Path within: " + path); return null; } /** * Remove slashes if there are too many, e.g. /foo//bar.html is being transformed into /foo/bar.html */ private String removeTooManySlashes(String path) { StringBuffer sb = new StringBuffer(); boolean previousCharWasSlash = false; for (int i = 0; i < path.length(); i++) { char c = path.charAt(i); if (c == '/' && previousCharWasSlash) { if (log.isDebugEnabled()) log.debug("Do not append this slash: " + i); } else { sb.append(c); } if (c == '/') { previousCharWasSlash = true; } else { previousCharWasSlash = false; } } return sb.toString(); } private Path getParentOfNewResource(org.wyona.commons.io.Path parent, String lookinPath) { Path parentOfNewResource = null; if(parent.equals("null")) { // if pathOfResourceCreator is ROOT parentOfNewResource = new Path("/" + lookinPath + "/"); } else if(parent.toString().equals("/")){ parentOfNewResource = new Path(parent + "/" + lookinPath + "/"); } else { parentOfNewResource = new Path("/" + lookinPath + "/"); } return parentOfNewResource; } private String getReferer() { if(request.getParameter("referer") != null) { return request.getParameter("referer"); } if(request.getHeader("referer") != null) { return replaceEntities(request.getHeader("referer")); } return PathUtil.backToRealm(getPath()); } /** * Replaces some characters by their corresponding xml entities. * This method escapes those characters which must not occur in an xml text node. * @param string * @return escaped string */ public String replaceEntities(String str) { // there may be some &amp; and some & mixed in the input, so first transform all // &amp; to & and then transform all & back to &amp; // this way we don't get double escaped &amp;amp; str = str.replaceAll("&amp;", "&"); str = str.replaceAll("&", "&amp;"); str = str.replaceAll("<", "&lt;"); return str; } } class Property { private String name; private String value; public Property(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public String getValue() { return value; } public String toString() { return name + " = " + value; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1240"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.wyona.yanel.servlet.toolbar.impl; import javax.servlet.http.HttpServletRequest; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.wyona.security.core.api.Identity; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.wyona.yanel.servlet.YanelServlet; import org.wyona.yanel.servlet.menu.Menu; import org.wyona.yanel.servlet.toolbar.YanelToolbar; import org.wyona.yanel.servlet.toolbar.YanelToolbarException; /** * The from scratch realm toolbar example, wrapping a {@link Menu}. */ public class FromScratchRealmToolbar implements YanelToolbar { private static Logger log = LogManager.getLogger(FromScratchRealmToolbar.class); private final Menu menu; public FromScratchRealmToolbar() { this.menu = new org.wyona.yanel.servlet.menu.impl.DefaultMenuV2(); } /** * @see org.wyona.yanel.servlet.toolbar.YanelToolbar#getToolbarBodyStart(Resource, HttpServletRequest, Map, String) */ public String getToolbarBodyStart(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) { try { String backToRealm = PathUtil.backToRealm(resource.getPath()); StringBuilder buf = new StringBuilder(); buf.append("<div id=\"yaneltoolbar_headerwrap\">"); buf.append("<div id=\"yaneltoolbar_menu\">"); buf.append(getToolbarMenus(resource, request, map, reservedPrefix)); buf.append("</div>"); buf.append(getInfo(resource, request, map, backToRealm, reservedPrefix)); buf.append("<span id=\"yaneltoolbar_logo\">"); buf.append("<a href=\"http: + "/yanel_toolbar_logo.png\" border=\"0\"/></a>"); buf.append("</span>"); buf.append("</div>"); buf.append("<div id=\"yaneltoolbar_middlewrap\">"); return buf.toString(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new YanelToolbarException("Couldn't generate toolbar body start markup: " + e.getMessage(), e); } } /** * @see org/wyona/yanel/servlet/toolbar/YanelToolbar#getToolbarHeader(Resource, HttpServletRequest, Map, String) */ public String getToolbarHeader(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) { String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath()); StringBuilder sb = new StringBuilder(); sb.append("<!-- START: Dynamically added code by " + this.getClass().getName() + " -->"); sb.append(System.getProperty("line.separator")); sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbar.css\" rel=\"stylesheet\"/>"); sb.append(System.getProperty("line.separator")); sb.append("<style type=\"text/css\" media=\"screen\">"); sb.append(System.getProperty("line.separator")); sb.append("#yaneltoolbar_menu li li.haschild{ background: lightgrey url(" + backToRealm + reservedPrefix + "/yanel-img/submenu.gif) no-repeat 98% 50%;}"); sb.append(System.getProperty("line.separator")); sb.append("#yaneltoolbar_menu li li.haschild:hover{ background: lightsteelblue url(" + backToRealm + reservedPrefix + "/yanel-img/submenu.gif) no-repeat 98% 50%;}"); sb.append("</style>"); sb.append(System.getProperty("line.separator")); // If browser is Mozilla (gecko engine rv:1.7) if (request.getHeader("User-Agent").indexOf("rv:1.7") >= 0) { sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarMozilla.css\" rel=\"stylesheet\"/>"); sb.append(System.getProperty("line.separator")); } // If browser is IE if (request.getHeader("User-Agent").indexOf("compatible; MSIE") >= 0 && request.getHeader("User-Agent").indexOf("Windows") >= 0) { sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarIE.css\" rel=\"stylesheet\"/>"); sb.append(System.getProperty("line.separator")); sb.append("<style type=\"text/css\" media=\"screen\">"); sb.append(" body{behavior:url(" + backToRealm + reservedPrefix + "/csshover.htc);font-size:100%;}"); sb.append("</style>"); } // If browser is IE6 if (request.getHeader("User-Agent").indexOf("compatible; MSIE 6") >= 0 && request.getHeader("User-Agent").indexOf("Windows") >= 0) { sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarIE6.css\" rel=\"stylesheet\"/>"); sb.append(System.getProperty("line.separator")); } sb.append("<!-- END: Dynamically added code by " + this.getClass().getName() + " -->"); return sb.toString(); } /** * @see org.wyona.yanel.servlet.toolbar.YanelToolbar#getToolbarBodyEnd(Resource, HttpServletRequest, Map, String) */ public String getToolbarBodyEnd(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) { return "</div>"; } /** * Gets the toolbar menus. */ private String getToolbarMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws Exception { return menu.getAllMenus(resource, request, map, reservedPrefix); } /** * Gets information such as realm name, user name, etc. */ private String getInfo(Resource resource, HttpServletRequest request, Map map, String backToRealm, String reservedPrefix) throws Exception { String userLanguage = getUserLanguage(resource); StringBuilder buf = new StringBuilder(); buf.append("<span id=\"yaneltoolbar_info\">"); //buf.append("Version: " + yanel.getVersion() + "-r" + yanel.getRevision() + "&#160;&#160;"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { VersionableV2 versionableRes = (VersionableV2) resource; if (versionableRes.isCheckedOut()) { buf.append(getLabel("page", userLanguage) + ": <b>Locked by " + versionableRes.getCheckoutUserID() + "</b> (<a href=\"?" + YanelServlet.YANEL_RESOURCE_USECASE + "=" + YanelServlet.RELEASE_LOCK + "\">unlock</a>)&#160;&#160;"); } } org.wyona.yarep.core.Node[] nodes = null; try { nodes = resource.getRealm().getRepository().getSearcher().searchProperty("workflow-state", "review", "/"); } catch(org.wyona.yarep.core.search.SearchException e) { log.error(e, e); // INFO: Do not throw exception in order to make it more fault tolerant, for example the SearchException is thrown if no index exists } if (nodes != null && nodes.length > 0) { buf.append("Workflow: <a href=\"" + backToRealm + reservedPrefix + "/workflow-dashboard.html?workflow-state=review\">" + nodes.length + " pages to be reviewed</a>&#160;&#160;"); } Identity identity = resource.getEnvironment().getIdentity(); if (identity != null && !identity.isWorld()) { buf.append(getLabel("user", userLanguage) + ": <b><a href=\"" + backToRealm + reservedPrefix + "/users/" + identity.getUsername() + ".html\" style=\"font-size: 13px; text-decoration: none;\">" + identity.getAlias() + "</a></b>"); } else { buf.append(getLabel("user", userLanguage) + ": <b>Not signed in!</b>"); } buf.append("</span>"); return buf.toString(); } /** * Gets user language (order: profile, browser, ...) (Also see * org/wyona/yanel/servlet/menu/Menu.java) */ private String getUserLanguage(Resource resource) throws Exception { Identity identity = resource.getEnvironment().getIdentity(); String language = resource.getRequestedLanguage(); String userID = identity.getUsername(); if (userID != null) { String userLanguage = resource.getRealm().getIdentityManager().getUserManager().getUser(userID).getLanguage(); if (userLanguage != null) { language = userLanguage; log.debug("Use user profile language: " + language); } else { log.debug("Use requested language: " + language); } } return language; } /** * Gets i18n (TODO: Replace this by something more generic) * * @param key I18n key * @param language Language */ private static String getLabel(String key, String language) { if (language.equals("de")) { if (key.equals("user")) { return "Benutzer"; } else if (key.equals("page")) { return "Seite"; } else { log.warn("Key '" + key + "' not supported yet by requested language '" + language + "'. Fallback to english!"); return getLabel(key, "en"); } } else if (language.equals("en")) { if (key.equals("user")) { return "User"; } else if (key.equals("page")) { return "Page"; } else { log.warn("Key '" + key + "' not supported yet!"); return key; } } else { log.warn("Language '" + language + "' not supported yet. Fallback to english!"); return getLabel(key, "en"); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1241"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.jboss.as.test.integration.management.cli; import java.io.IOException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient public class WildCardReadsTestCase extends AbstractCliTestBase { /* * This address meets a particular set of requirements needed to validate the WFLY-2527 fix: * 1) the distributed-cache=dist resource does not actually exist. Therefore eviction=XXX child resources also do not * TBH I'm not certain this aspect is all that critical, but don't blindly remove it. * 2) There is no ManagementResourceRegistration for eviction=* * 3) There are MRR's for eviction=XXX, eviction=YYY, etc * 4) The descriptions for each of those eviction=XXX, eviction=YYY, etc are identical * * TODO add some assertions that validate that 1-4 still hold true, in order to ensure the test continues * to validate the expected behavior */ private static final String OP_PATTERN = "/subsystem=infinispan/cache-container=web/distributed-cache=dist/eviction=%s:%s"; private static final String READ_OP_DESC_OP = ModelDescriptionConstants.READ_OPERATION_DESCRIPTION_OPERATION + "(name=%s)"; private static final String READ_RES_DESC_OP = ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION + "(access-control=combined-descriptions,operations=true,recursive=true)"; private static final String EVICTION = "EVICTION"; @BeforeClass public static void before() throws Exception { initCLI(); } @AfterClass public static void after() throws Exception { closeCLI(); } /** * Tests WFLY-2527 added behavior of supporting read-operation-description for * wildcard addresses where there is no generic resource registration for the type */ @Test public void testLenientReadOperationDescription() throws IOException { cli.sendLine(String.format(OP_PATTERN, EVICTION, ModelDescriptionConstants.READ_OPERATION_NAMES_OPERATION)); CLIOpResult opResult = cli.readAllAsOpResult(); Assert.assertTrue(opResult.isIsOutcomeSuccess()); for (ModelNode node : opResult.getResponseNode().get(ModelDescriptionConstants.RESULT).asList()) { String opPart = String.format(READ_OP_DESC_OP, node.asString()); cli.sendLine(String.format(OP_PATTERN, EVICTION, opPart)); opResult = cli.readAllAsOpResult(); Assert.assertTrue(opResult.isIsOutcomeSuccess()); ModelNode specific = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT); cli.sendLine(String.format(OP_PATTERN, "*", opPart)); opResult = cli.readAllAsOpResult(); Assert.assertTrue(opResult.isIsOutcomeSuccess()); Assert.assertEquals("mismatch for " + node.asString(), specific, opResult.getResponseNode().get(ModelDescriptionConstants.RESULT)); } } /** * Tests WFLY-2527 fix. */ @Test public void testReadResourceDescriptionNoGenericRegistration() throws IOException { cli.sendLine(String.format(OP_PATTERN, EVICTION, READ_RES_DESC_OP)); CLIOpResult opResult = cli.readAllAsOpResult(); Assert.assertTrue(opResult.isIsOutcomeSuccess()); ModelNode specific = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT); cli.sendLine(String.format(OP_PATTERN, "*", READ_RES_DESC_OP)); opResult = cli.readAllAsOpResult(); Assert.assertTrue(opResult.isIsOutcomeSuccess()); ModelNode generic = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT); Assert.assertEquals(ModelType.LIST, generic.getType()); Assert.assertEquals(1, generic.asInt()); Assert.assertEquals(specific, generic.get(0).get(ModelDescriptionConstants.RESULT)); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1242"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">public class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> temp = new HashSet<>(); for (int i = 0; i < nums1.length; i++) { temp.add(nums1[i]); } } List<Integer> numbers = new ArrayList<>(); for (int i = 0; i < nums2.length; i++) { if (temp.contains(nums2[i])) { numbers.add(nums2[i]); temp.remove(nums2[i]); } } // transfer array int newArray[] = new int[numbers.size()]; for (int i = 0; i < numbers.size(); i++) { newArray[i] = numbers.get(i); } return newArray; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1243"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.geom.Point2D; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.vecmath.Matrix4f; import javax.vecmath.Point3d; import javax.vecmath.Quat4f; import javax.vecmath.Vector2f; import javax.vecmath.Vector3f; /// Extends the simple renderer with a Trackball controller public class ArcballRenderer extends SimpleRenderer { private Matrix4f LastRot = new Matrix4f(); private ArcBallHelper arcBall = null; private Arcball arcball_geo = new Arcball(); /** Controls zoom speed */ float scale_move_ratio = .05f; /// TODO make the zoom ratio exposed! /** Controls pan speed */ float pan_move_ratio = 1; public ArcballRenderer(GLCanvas canvas) { super(canvas); LastRot.setIdentity(); arcBall = new ArcBallHelper(canvas.getWidth(), canvas.getHeight()); adjust_pan_speed(canvas.getWidth(), canvas.getHeight()); } /** Make sure panning speed is ~constant * TODO use it*/ private void adjust_pan_speed(int width, int height){ /// Pan speed adjusted normalized w.r.t. window size pan_move_ratio = 1.0f / ((float) canvas.getWidth()); // System.out.printf("pan_move_ratio: %f\n", pan_move_ratio); } @Override public void display(GLAutoDrawable drawable) { GL gl = drawable.getGL(); gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); // Make unit sphere fit loosely gl.glScaled(.85, .85, .85); // Arcball rotates, but doesn't translate/scale gl.glMultMatrixf(super.getRotation(), 0); arcball_geo.draw(gl); // Models are also scaled translated gl.glScaled(getScale(), getScale(), getScale()); gl.glTranslated(getTx(),getTy(),getTz()); for (int i = 0; i < objects.size(); i++) objects.elementAt(i).draw(gl); gl.glFlush(); } @Override // Arcball needs to know about window geometry public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { super.reshape(drawable, x, y, width, height); arcBall.setBounds(width, height); adjust_pan_speed(width,height); } @Override public void mousePressed(MouseEvent mouseEvent) { switch (mouseEvent.getButton()) { case MouseEvent.BUTTON1: // Left Mouse Point MousePt = mouseEvent.getPoint(); LastRot.set(model_matrix); arcBall.click(MousePt); default: return; } } @Override public void mouseDragged(MouseEvent mouseEvent) { switch (mouseEvent.getButton()) { case MouseEvent.BUTTON1: // Left Mouse // Update the model matrix Point MousePt = mouseEvent.getPoint(); Quat4f ThisQuat = new Quat4f(); arcBall.drag(MousePt, ThisQuat); model_matrix.setRotation(ThisQuat); model_matrix.mul(model_matrix, LastRot); break; case MouseEvent.BUTTON2: // Middle Mouse System.out.printf("TODO: PANNING \n"); break; default: return; } // Finally refresh the OpenGL window canvas.display(); } @Override public void mouseClicked(MouseEvent event) { if (event.getClickCount() == 2) { System.out.println("double clicked"); } } @Override public void mouseWheelMoved(MouseWheelEvent e){ setScale( getScale()*(1 + (scale_move_ratio*e.getWheelRotation()) )); canvas.display(); } /** * The math to implementing ArcBall functionality */ class ArcBallHelper { private static final float Epsilon = 1.0e-5f; Vector3f StVec; //Saved click vector Vector3f EnVec; //Saved drag vector float adjustWidth; //Mouse bounds width float adjustHeight; //Mouse bounds height public ArcBallHelper(float NewWidth, float NewHeight) { StVec = new Vector3f(); EnVec = new Vector3f(); setBounds(NewWidth, NewHeight); } public void mapToSphere(Point point, Vector3f vector) { //Copy paramter into temp point Vector2f tempPoint = new Vector2f(point.x, point.y); //Adjust point coords and scale down to range of [-1 ... 1] tempPoint.x = (tempPoint.x * this.adjustWidth) - 1.0f; tempPoint.y = 1.0f - (tempPoint.y * this.adjustHeight); //Compute the square of the length of the vector to the point from the center float length = (tempPoint.x * tempPoint.x) + (tempPoint.y * tempPoint.y); //If the point is mapped outside of the sphere... (length > radius squared) if (length > 1.0f) { //Compute a normalizing factor (radius / sqrt(length)) float norm = (float) (1.0 / Math.sqrt(length)); //Return the "normalized" vector, a point on the sphere vector.x = tempPoint.x * norm; vector.y = tempPoint.y * norm; vector.z = 0.0f; } else //Else it's on the inside { //Return a vector to a point mapped inside the sphere sqrt(radius squared - length) vector.x = tempPoint.x; vector.y = tempPoint.y; vector.z = (float) Math.sqrt(1.0f - length); } } public void setBounds(float NewWidth, float NewHeight) { assert((NewWidth > 1.0f) && (NewHeight > 1.0f)); //Set adjustment factor for width/height adjustWidth = 1.0f / ((NewWidth - 1.0f) * 0.5f); adjustHeight = 1.0f / ((NewHeight - 1.0f) * 0.5f); } //Mouse down public void click(Point NewPt) { mapToSphere(NewPt, this.StVec); } //Mouse drag, calculate rotation public void drag(Point NewPt, Quat4f NewRot) { //Map the point to the sphere this.mapToSphere(NewPt, EnVec); //Return the quaternion equivalent to the rotation if (NewRot != null) { Vector3f Perp = new Vector3f(); //Compute the vector perpendicular to the begin and end vectors Perp.cross(StVec,EnVec); //Compute the length of the perpendicular vector if (Perp.length() > Epsilon) //if its non-zero { //We're ok, so return the perpendicular vector as the transform after all NewRot.x = Perp.x; NewRot.y = Perp.y; NewRot.z = Perp.z; //In the quaternion values, w is cosine (theta / 2), where theta is rotation angle NewRot.w = StVec.dot(EnVec); } else //if its zero { //The begin and end vectors coincide, so return an identity transform NewRot.x = NewRot.y = NewRot.z = NewRot.w = 0.0f; } } } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1244"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package pair; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.ToDoubleBiFunction; import java.util.function.ToDoubleFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToIntFunction; import java.util.function.ToLongBiFunction; import java.util.function.ToLongFunction; import java.util.function.UnaryOperator; public class Pair<A, B> { public static <A, B> Pair<A, B> make(final A left, final B right) { return new Pair<>(left, right); } public static <A> Pair<A, A> of(final A item) { return make(item, item); } public final A left; public final B right; public final A left() { return left; } public final B right() { return right; } public final Pair<B, A> invert() { return Pair.make(right, left); } protected Pair(final A a, final B b) { left = a; right = b; } public <R> R intoFun(final BiFunction<A, B, R> fun) { return fun.apply(left, right); } public void intoCon(final BiConsumer<A, B> fun) { fun.accept(left, right); } public <R> R intoFun(final Function<Pair<A, B>, R> fun) { return fun.apply(this); } public void intoCon(final Consumer<Pair<A, B>> fun) { fun.accept(this); } public double intoDouble(final ToDoubleFunction<Pair<A, B>> fun) { return fun.applyAsDouble(this); } public double intoDouble(final ToDoubleBiFunction<A, B> fun) { return fun.applyAsDouble(left, right); } public int intoInt(final ToIntFunction<Pair<A, B>> fun) { return fun.applyAsInt(this); } public int intoInt(final ToIntBiFunction<A, B> fun) { return fun.applyAsInt(left, right); } public long intoLong(final ToLongFunction<Pair<A, B>> fun) { return fun.applyAsLong(this); } public long intoLong(final ToLongBiFunction<A, B> fun) { return fun.applyAsLong(left, right); } public Pair<A, B> intoPair(final UnaryOperator<Pair<A, B>> fun) { return fun.apply(this); } public boolean intoPred(final Predicate<Pair<A, B>> fun) { return fun.test(this); } public boolean intoPred(final BiPredicate<A, B> fun) { return fun.test(left, right); } public <R> Pair<R, B> mapLeft(final Function<A, R> fun) { return Pair.make(fun.apply(left), right); } public <R> Pair<A, R> mapRight(final Function<B, R> fun) { return Pair.make(left, fun.apply(right)); } public <R> Pair<R, B> mapLeft(final R neoLiberal) { return Pair.make(neoLiberal, right); } public Pair<A, B> replaceLeft(final A neoLiberal) { return Pair.make(neoLiberal, right); } public <R> Pair<A, R> mapRight(final R altRight) { return Pair.make(left, altRight); } public Pair<A, B> replaceRight(final B altRight) { return Pair.make(left, altRight); } public static final class F { public static final <A, B> Function<A, Pair<A, B>> partialRight( final B right) { return left -> Pair.make(left, right); } public static final <A, B> Function<B, Pair<A, B>> partialLeft( final A left) { return right -> Pair.make(left, right); } public static final <A, B, R> Function<Pair<A, B>, Pair<R, B>> mapLeft( final Function<A, R> fun) { return pair -> pair.mapLeft(fun); } public static final <A, B, R> Function<Pair<A, B>, Pair<A, R>> mapRight( final Function<B, R> fun) { return pair -> pair.mapRight(fun); } public static final <A, B, R> Function<Pair<A, B>, Pair<R, B>> mapLeft( final R neoLiberal) { return pair -> pair.mapLeft(neoLiberal); } public static final <A, B, R> Function<Pair<A, B>, Pair<A, R>> mapRight( final R altRight) { return pair -> pair.mapRight(altRight); } public static final <A, B> UnaryOperator<Pair<A, B>> replaceLeft( A neoLiberal) { return pair -> pair.replaceLeft(neoLiberal); } public static final <A, B> UnaryOperator<Pair<A, B>> replaceRight( B altRight) { return pair -> pair.replaceRight(altRight); } public static final <A, B, R> Function<Pair<A, B>, R> intoFun( final BiFunction<A, B, R> fun) { return pair -> pair.intoFun(fun); } public static final <A, B> UnaryOperator<Pair<A, B>> intoPair( final UnaryOperator<Pair<A, B>> fun) { return pair -> pair.intoFun(fun); } public static final <A, B> ToDoubleFunction<Pair<A, B>> intoDouble( final ToDoubleFunction<Pair<A, B>> fun) { return pair -> pair.intoDouble(fun); } public static final <A, B> ToDoubleFunction<Pair<A, B>> intoDouble( final ToDoubleBiFunction<A, B> fun) { return pair -> pair.intoDouble(fun); } public static final <A, B> Consumer<Pair<A, B>> intoCon( final BiConsumer<A, B> fun) { return pair -> pair.intoCon(fun); } public static final <A, B> Predicate<Pair<A, B>> intoPred( final BiPredicate<A, B> pred) { return pair -> pair.intoPred(pred); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1245"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.jpos.iso; import org.jpos.core.Configurable; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.util.*; import java.io.EOFException; import java.io.IOException; import java.io.InterruptedIOException; import java.io.PrintStream; import java.lang.ref.WeakReference; import java.net.*; import java.util.*; /** * Accept ServerChannel sessions and forwards them to ISORequestListeners * @author Alejandro P. Revilla * @author Bharavi Gade * @version $Revision$ $Date$ */ public class ISOServer extends Observable implements LogSource, Runnable, Observer, ISOServerMBean, Configurable, Loggeable, ISOServerSocketFactory { int port; protected ISOChannel clientSideChannel; ISOPackager clientPackager; protected Collection clientOutgoingFilters, clientIncomingFilters, listeners; ThreadPool pool; public static final int DEFAULT_MAX_THREADS = 100; public static final String LAST = ":last"; String name; protected long lastTxn = 0l; protected Logger logger; protected String realm; protected String realmChannel; protected ISOServerSocketFactory socketFactory = null; public static final int CONNECT = 0; public static final int SIZEOF_CNT = 1; private int[] cnt; private String[] allow; private InetAddress bindAddr; private int backlog; protected Configuration cfg; private boolean shutdown = false; private ServerSocket serverSocket; private Map channels; protected boolean ignoreISOExceptions; /** * @param port port to listen * @param clientSide client side ISOChannel (where we accept connections) * @param pool ThreadPool (created if null) */ public ISOServer(int port, ServerChannel clientSide, ThreadPool pool) { super(); this.port = port; this.clientSideChannel = clientSide; this.clientPackager = clientSide.getPackager(); if (clientSide instanceof FilteredChannel) { FilteredChannel fc = (FilteredChannel) clientSide; this.clientOutgoingFilters = fc.getOutgoingFilters(); this.clientIncomingFilters = fc.getIncomingFilters(); } this.pool = (pool == null) ? new ThreadPool (1, DEFAULT_MAX_THREADS) : pool; listeners = new Vector(); name = ""; channels = new HashMap(); cnt = new int[SIZEOF_CNT]; } protected Session createSession (ServerChannel channel) { return new Session (channel); } protected class Session implements Runnable, LogSource { ServerChannel channel; String realm; protected Session(ServerChannel channel) { this.channel = channel; realm = ISOServer.this.getRealm() + ".session"; } public void run() { setChanged (); notifyObservers (); if (channel instanceof BaseChannel) { LogEvent ev = new LogEvent (this, "session-start"); Socket socket = ((BaseChannel)channel).getSocket (); realm = realm + "/" + socket.getInetAddress().getHostAddress() + ":" + socket.getPort(); try { checkPermission (socket, ev); } catch (ISOException e) { try { int delay = 1000 + new Random().nextInt (4000); ev.addMessage (e.getMessage()); ev.addMessage ("delay=" + delay); ISOUtil.sleep (delay); socket.close (); } catch (IOException ioe) { ev.addMessage (ioe); } return; } finally { Logger.log (ev); } } try { for (;;) { try { ISOMsg m = channel.receive(); lastTxn = System.currentTimeMillis(); Iterator iter = listeners.iterator(); while (iter.hasNext()) if (((ISORequestListener)iter.next()).process (channel, m)) break; } catch (ISOFilter.VetoException e) { Logger.log (new LogEvent (this, "VetoException", e.getMessage())); } catch (ISOException e) { if (ignoreISOExceptions) { Logger.log (new LogEvent (this, "ISOException", e.getMessage())); } else throw e; } } } catch (EOFException e) { // Logger.log (new LogEvent (this, "session-warning", "<eof/>")); } catch (SocketException e) { // if (!shutdown) // Logger.log (new LogEvent (this, "session-warning", e)); } catch (InterruptedIOException e) { // nothing to log } catch (Throwable e) { Logger.log (new LogEvent (this, "session-error", e)); } try { channel.disconnect(); } catch (IOException ex) { Logger.log (new LogEvent (this, "session-error", ex)); } Logger.log (new LogEvent (this, "session-end")); } public void setLogger (Logger logger, String realm) { } public String getRealm () { return realm; } public Logger getLogger() { return ISOServer.this.getLogger(); } public void checkPermission (Socket socket, LogEvent evt) throws ISOException { if (allow != null && allow.length > 0) { String ip = socket.getInetAddress().getHostAddress (); for (int i=0; i<allow.length; i++) { if (ip.equals (allow[i])) { evt.addMessage ("access granted, ip=" + ip); return; } } throw new ISOException ("access denied, ip=" + ip); } } } /** * add an ISORequestListener * @param l request listener to be added * @see ISORequestListener */ public void addISORequestListener(ISORequestListener l) { listeners.add (l); } /** * remove an ISORequestListener * @param l a request listener to be removed * @see ISORequestListener */ public void removeISORequestListener(ISORequestListener l) { listeners.remove (l); } /** * Shutdown this server */ public void shutdown () { shutdown = true; new Thread ("ISOServer-shutdown") { public void run () { shutdownServer (); if (!cfg.getBoolean ("keep-channels")) shutdownChannels (); } }.start(); } private void shutdownServer () { try { if (serverSocket != null) serverSocket.close (); if (pool != null) pool.close(); } catch (IOException e) { Logger.log (new LogEvent (this, "shutdown", e)); } } private void shutdownChannels () { Iterator iter = channels.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); WeakReference ref = (WeakReference) entry.getValue(); ISOChannel c = (ISOChannel) ref.get (); if (c != null) { try { c.disconnect (); } catch (IOException e) { Logger.log (new LogEvent (this, "shutdown", e)); } } } } private void purgeChannels () { Iterator iter = channels.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); WeakReference ref = (WeakReference) entry.getValue(); ISOChannel c = (ISOChannel) ref.get (); if (c == null || (!c.isConnected())) iter.remove (); } } public ServerSocket createServerSocket(int port) throws IOException { ServerSocket ss = new ServerSocket(); try { ss.setReuseAddress(true); ss.bind(new InetSocketAddress(bindAddr, port), backlog); } catch(SecurityException e) { ss.close(); throw e; } catch(IOException e) { ss.close(); throw e; } return ss; } public void run() { ServerChannel channel; if (socketFactory == null) socketFactory = this; serverLoop : while (!shutdown) { try { serverSocket = socketFactory.createServerSocket(port); Logger.log (new LogEvent (this, "iso-server", "listening on " + (bindAddr != null ? bindAddr + ":" : "port ") + port + (backlog > 0 ? " backlog="+backlog : "") )); while (!shutdown) { try { if (pool.getAvailableCount() <= 0) { try { serverSocket.close(); } catch (IOException e){ Logger.log (new LogEvent (this, "iso-server", e)); relax(); } for (int i=0; pool.getIdleCount() == 0; i++) { if (shutdown) break serverLoop; if (i % 240 == 0 && cfg.getBoolean("pool-exhaustion-warning", true)) { LogEvent evt = new LogEvent (this, "warn"); evt.addMessage ( "pool exhausted " + serverSocket.toString() ); evt.addMessage (pool); Logger.log (evt); } ISOUtil.sleep (250); } serverSocket = socketFactory.createServerSocket(port); } channel = (ServerChannel) clientSideChannel.clone(); channel.accept (serverSocket); if ((cnt[CONNECT]++) % 100 == 0) purgeChannels (); WeakReference wr = new WeakReference (channel); channels.put (channel.getName(), wr); channels.put (LAST, wr); pool.execute (createSession(channel)); setChanged (); notifyObservers (this); if (channel instanceof Observable) ((Observable)channel).addObserver (this); } catch (SocketException e) { if (!shutdown) { Logger.log (new LogEvent (this, "iso-server", e)); relax(); continue serverLoop; } } catch (IOException e) { Logger.log (new LogEvent (this, "iso-server", e)); relax(); } } } catch (Throwable e) { Logger.log (new LogEvent (this, "iso-server", e)); relax(); } } } private void relax() { try { Thread.sleep (5000); } catch (InterruptedException e) { } } /** * associates this ISOServer with a name using NameRegistrar * @param name name to register * @see NameRegistrar */ public void setName (String name) { this.name = name; NameRegistrar.register ("server."+name, this); } /** * @return ISOServer instance with given name. * @throws NameRegistrar.NotFoundException; * @see NameRegistrar */ public static ISOServer getServer (String name) throws NameRegistrar.NotFoundException { return (ISOServer) NameRegistrar.get ("server."+name); } /** * @return this ISOServer's name ("" if no name was set) */ public String getName() { return this.name; } public void setLogger (Logger logger, String realm) { this.logger = logger; this.realm = realm; this.realmChannel = realm + ".channel"; } public String getRealm () { return realm; } public Logger getLogger() { return logger; } public void update(Observable o, Object arg) { setChanged (); notifyObservers (arg); } /** * Gets the ISOClientSocketFactory (may be null) * @see ISOClientSocketFactory * @since 1.3.3 */ public ISOServerSocketFactory getSocketFactory() { return socketFactory; } /** * Sets the specified Socket Factory to create sockets * @param socketFactory the ISOClientSocketFactory * @see ISOClientSocketFactory * @since 1.3.3 */ public void setSocketFactory(ISOServerSocketFactory socketFactory) { this.socketFactory = socketFactory; } public int getPort () { return port; } public void resetCounters () { cnt = new int[SIZEOF_CNT]; lastTxn = 0l; } /** * @return number of connections accepted by this server */ public int getConnectionCount () { return cnt[CONNECT]; } // ThreadPoolMBean implementation (delegate calls to pool) public int getJobCount () { return pool.getJobCount(); } public int getPoolSize () { return pool.getPoolSize(); } public int getMaxPoolSize () { return pool.getMaxPoolSize(); } public int getIdleCount() { return pool.getIdleCount(); } public int getPendingCount () { return pool.getPendingCount(); } public int getActiveConnections () { return pool.getActiveCount(); } /** * @return most recently connected ISOChannel or null */ public ISOChannel getLastConnectedISOChannel () { return getISOChannel (LAST); } /** * @return ISOChannel under the given name */ public ISOChannel getISOChannel (String name) { WeakReference ref = (WeakReference) channels.get (name); if (ref != null) return (ISOChannel) ref.get (); return null; } public void setConfiguration (Configuration cfg) throws ConfigurationException { this.cfg = cfg; allow = cfg.getAll ("allow"); backlog = cfg.getInt ("backlog", 0); ignoreISOExceptions = cfg.getBoolean("ignore-iso-exceptions"); String ip = cfg.get ("bind-address", null); if (ip != null) { try { bindAddr = InetAddress.getByName (ip); } catch (UnknownHostException e) { throw new ConfigurationException ("Invalid bind-address " + ip, e); } } if (socketFactory == null) socketFactory = this; if (socketFactory != this && socketFactory instanceof Configurable) { ((Configurable)socketFactory).setConfiguration (cfg); } } public String getISOChannelNames () { StringBuilder sb = new StringBuilder (); Iterator iter = channels.entrySet().iterator(); for (int i=0; iter.hasNext(); i++) { Map.Entry entry = (Map.Entry) iter.next(); WeakReference ref = (WeakReference) entry.getValue(); ISOChannel c = (ISOChannel) ref.get (); if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) { if (i > 0) sb.append (' '); sb.append (entry.getKey()); } } return sb.toString(); } public String getCountersAsString () { StringBuilder sb = new StringBuilder (); int cnt[] = getCounters(); sb.append ("connected="); sb.append (Integer.toString(cnt[0])); sb.append (", rx="); sb.append (Integer.toString(cnt[0])); sb.append (", tx="); sb.append (Integer.toString(cnt[1])); sb.append (", last="); sb.append (lastTxn); if (lastTxn > 0) { sb.append (", idle="); sb.append(System.currentTimeMillis() - lastTxn); sb.append ("ms"); } return sb.toString(); } public int[] getCounters() { Iterator iter = channels.entrySet().iterator(); int[] cnt = new int[3]; cnt[2] = 0; for (int i=0; iter.hasNext(); i++) { Map.Entry entry = (Map.Entry) iter.next(); WeakReference ref = (WeakReference) entry.getValue(); ISOChannel c = (ISOChannel) ref.get (); if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) { cnt[2]++; if (c instanceof BaseChannel) { int[] cc = ((BaseChannel)c).getCounters(); cnt[0] += cc[ISOChannel.RX]; cnt[1] += cc[ISOChannel.TX]; } } } return cnt; } public int getTXCounter() { int cnt[] = getCounters(); return cnt[1]; } public int getRXCounter() { int cnt[] = getCounters(); return cnt[0]; } public int getConnections () { int cnt[] = getCounters(); return cnt[2]; } public long getLastTxnTimestampInMillis() { return lastTxn; } public long getIdleTimeInMillis() { return lastTxn > 0L ? System.currentTimeMillis() - lastTxn : -1L; } public String getCountersAsString (String isoChannelName) { ISOChannel channel = getISOChannel(isoChannelName); StringBuffer sb = new StringBuffer(); if (channel instanceof BaseChannel) { int[] counters = ((BaseChannel)channel).getCounters(); append (sb, "rx=", counters[ISOChannel.RX]); append (sb, ", tx=", counters[ISOChannel.TX]); append (sb, ", connects=", counters[ISOChannel.CONNECT]); } return sb.toString(); } public void dump (PrintStream p, String indent) { p.println (indent + getCountersAsString()); Iterator iter = channels.entrySet().iterator(); String inner = indent + " "; for (int i=0; iter.hasNext(); i++) { Map.Entry entry = (Map.Entry) iter.next(); WeakReference ref = (WeakReference) entry.getValue(); ISOChannel c = (ISOChannel) ref.get (); if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) { if (c instanceof BaseChannel) { StringBuilder sb = new StringBuilder (); int[] cc = ((BaseChannel)c).getCounters(); sb.append (inner); sb.append (entry.getKey()); sb.append (": rx="); sb.append (Integer.toString (cc[ISOChannel.RX])); sb.append (", tx="); sb.append (Integer.toString (cc[ISOChannel.TX])); sb.append (", last="); sb.append (Long.toString(lastTxn)); p.println (sb.toString()); } } } } private void append (StringBuffer sb, String name, int value) { sb.append (name); sb.append (value); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1246"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.intellij.codeInspection.varScopeCanBeNarrowed; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInspection.InspectionManager; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ex.BaseLocalInspectionTool; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.VariableKind; import com.intellij.psi.controlFlow.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.util.IJSwingUtilities; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashSet; import java.util.*; /** * @author ven */ public class FieldCanBeLocalInspection extends BaseLocalInspectionTool { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.varScopeCanBeNarrowed.FieldCanBeLocalInspection"); public static final String SHORT_NAME = "FieldCanBeLocal"; public String getGroupDisplayName() { return GroupNames.CLASSLAYOUT_GROUP_NAME; } public String getDisplayName() { return "Field can be local"; } public String getShortName() { return SHORT_NAME; } public ProblemDescriptor[] checkClass(PsiClass aClass, InspectionManager manager, boolean isOnTheFly) { PsiManager psiManager = aClass.getManager(); final Set<PsiField> candidates = new LinkedHashSet<PsiField>(); final PsiClass topLevelClass = PsiUtil.getTopLevelClass(aClass); if (topLevelClass == null) return null; final PsiField[] fields = aClass.getFields(); NextField: for (PsiField field : fields) { if (field.hasModifierProperty(PsiModifier.PRIVATE)) { final PsiReference[] refs = psiManager.getSearchHelper().findReferences(field, GlobalSearchScope.allScope(psiManager.getProject()), false); for (PsiReference ref : refs) { PsiElement element = ref.getElement(); while (element != null) { if (element instanceof PsiMethod) { candidates.add(field); continue NextField; } element = PsiTreeUtil.getParentOfType(element, PsiMember.class); } continue NextField; } } } topLevelClass.accept(new PsiRecursiveElementVisitor() { public void visitElement(PsiElement element) { if (candidates.size() > 0) super.visitElement(element); } public void visitMethod(PsiMethod method) { super.visitMethod(method); final PsiCodeBlock body = method.getBody(); if (body != null) { try { final ControlFlow controlFlow = ControlFlowFactory.getControlFlow(body, AllVariablesControlFlowPolicy.getInstance()); final List<PsiReferenceExpression> readBeforeWrite = ControlFlowUtil.getReadBeforeWrite(controlFlow); for (Iterator<PsiReferenceExpression> iterator = readBeforeWrite.iterator(); iterator.hasNext();) { final PsiElement resolved = iterator.next().resolve(); if (resolved instanceof PsiField) { final PsiField field = (PsiField)resolved; candidates.remove(field); } } } catch (AnalysisCanceledException e) { candidates.clear(); } } } }); if (candidates.isEmpty()) return null; ProblemDescriptor[] result = new ProblemDescriptor[candidates.size()]; int i = 0; for (Iterator<PsiField> iterator = candidates.iterator(); iterator.hasNext(); i++) { PsiField field = iterator.next(); final String message = "Field can be converted to one or more local variables."; result[i] = manager.createProblemDescriptor(field, message, new MyQuickFix(field), ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } return result; } private static class MyQuickFix implements LocalQuickFix { private PsiField myField; public MyQuickFix(final PsiField field) { myField = field; } public String getName() { return "Convert to local"; } public void applyFix(Project project, ProblemDescriptor descriptor) { if (!myField.isValid()) return; //weird. should not get here when field becomes invalid PsiManager manager = PsiManager.getInstance(project); PsiSearchHelper helper = manager.getSearchHelper(); Set<PsiMethod> methodSet = new HashSet<PsiMethod>(); final PsiReference[] allRefs = helper.findReferences(myField, GlobalSearchScope.allScope(project), false); for (PsiReference ref : allRefs) { if (ref instanceof PsiReferenceExpression) { final PsiMethod method = PsiTreeUtil.getParentOfType((PsiReferenceExpression)ref, PsiMethod.class); LOG.assertTrue(method != null); methodSet.add(method); } } PsiElement newCaretPosition = null; for (PsiMethod method : methodSet) { final PsiReference[] refs = helper.findReferences(myField, new LocalSearchScope(method), true); LOG.assertTrue(refs.length > 0); Set<PsiReference> refsSet = new HashSet<PsiReference>(Arrays.asList(refs)); PsiCodeBlock anchorBlock = findAnchorBlock(refs); LOG.assertTrue(anchorBlock != null); final PsiElementFactory elementFactory = manager.getElementFactory(); final CodeStyleManager styleManager = manager.getCodeStyleManager(); final String propertyName = styleManager.variableNameToPropertyName(myField.getName(), VariableKind.FIELD); String localName = styleManager.propertyNameToVariableName(propertyName, VariableKind.LOCAL_VARIABLE); localName = RefactoringUtil.suggestUniqueVariableName(localName, anchorBlock, myField); try { final PsiElement anchor = getAnchorElement(anchorBlock, refs); final PsiElement newDeclaration; if (anchor instanceof PsiExpressionStatement && ((PsiExpressionStatement)anchor).getExpression() instanceof PsiAssignmentExpression) { final PsiAssignmentExpression expression = (PsiAssignmentExpression)((PsiExpressionStatement)anchor).getExpression(); if (expression.getLExpression() instanceof PsiReferenceExpression && ((PsiReferenceExpression)expression.getLExpression()).isReferenceTo(myField)) { final PsiExpression initializer = expression.getRExpression(); final PsiDeclarationStatement decl = elementFactory.createVariableDeclarationStatement(localName, myField.getType(), initializer); newDeclaration = anchor.replace(decl); refsSet.remove(expression.getLExpression()); retargetReferences(elementFactory, localName, refsSet); } else { newDeclaration = addDeclarationWithoutInitializerAndRetargetReferences(elementFactory, localName, anchorBlock, anchor, refsSet); } } else { newDeclaration = addDeclarationWithoutInitializerAndRetargetReferences(elementFactory, localName, anchorBlock, anchor, refsSet); } if (newCaretPosition == null) { newCaretPosition = newDeclaration; } } catch (IncorrectOperationException e) { LOG.error(e); } } if (newCaretPosition != null) { final PsiFile psiFile = myField.getContainingFile(); final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null && IJSwingUtilities.hasFocus(editor.getComponent())) { final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == psiFile) { editor.getCaretModel().moveToOffset(newCaretPosition.getTextOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } } } try { myField.normalizeDeclaration(); myField.delete(); } catch (IncorrectOperationException e) { LOG.error(e); } } private void retargetReferences(final PsiElementFactory elementFactory, final String localName, final Set<PsiReference> refs) throws IncorrectOperationException { final PsiReferenceExpression refExpr = (PsiReferenceExpression)elementFactory.createExpressionFromText(localName, null); for (PsiReference ref : refs) { if (ref instanceof PsiReferenceExpression) { ((PsiReferenceExpression)ref).replace(refExpr); } } } private PsiElement addDeclarationWithoutInitializerAndRetargetReferences(final PsiElementFactory elementFactory, final String localName, final PsiCodeBlock anchorBlock, final PsiElement anchor, final Set<PsiReference> refs) throws IncorrectOperationException { final PsiElement newDeclaration; final PsiDeclarationStatement decl = elementFactory.createVariableDeclarationStatement(localName, myField.getType(), null); newDeclaration = anchorBlock.addBefore(decl, anchor); retargetReferences(elementFactory, localName, refs); return newDeclaration; } public String getFamilyName() { return getName(); } private static PsiElement getAnchorElement(final PsiCodeBlock anchorBlock, final PsiReference[] refs) { PsiElement firstElement = null; for (PsiReference reference : refs) { final PsiElement element = reference.getElement(); if (firstElement == null || firstElement.getTextRange().getStartOffset() > element.getTextRange().getStartOffset()) { firstElement = element; } } LOG.assertTrue(firstElement != null); while (firstElement.getParent() != anchorBlock) { firstElement = firstElement.getParent(); } return firstElement; } private static PsiCodeBlock findAnchorBlock(final PsiReference[] refs) { PsiCodeBlock result = null; for (PsiReference psiReference : refs) { final PsiElement element = psiReference.getElement(); PsiCodeBlock block = PsiTreeUtil.getParentOfType(element, PsiCodeBlock.class); if (result == null) { result = block; } else { final PsiElement commonParent = PsiTreeUtil.findCommonParent(result, block); result = PsiTreeUtil.getParentOfType(commonParent, PsiCodeBlock.class, false); } } return result; } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1247"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package ca.bc.gov.restrictions; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.nuxeo.ecm.core.api.security.ACE; import org.nuxeo.ecm.core.api.security.ACL; import org.nuxeo.ecm.core.api.security.ACP; import org.nuxeo.ecm.core.api.security.Access; import org.nuxeo.ecm.core.api.security.SecurityConstants; import org.nuxeo.ecm.core.model.Document; import org.nuxeo.ecm.core.security.AbstractSecurityPolicy; import ca.bc.gov.utils.CustomSecurityConstants; /** * Language recorders policies */ public class LanguageRecorders extends AbstractSecurityPolicy { private static ArrayList<String> allowedDocumentTypes = new ArrayList<String>(); private Boolean hasPermissionInACP(ACP mergedAcp, List<String> additionalPrincipalsList, String permission) { for (ACL acl : mergedAcp.getACLs()) { for (ACE ace : acl.getACEs()) { if (ace.isGranted() && additionalPrincipalsList.contains(ace.getUsername()) && ace.getPermission().equals(permission) ) { return true; } } } return false; } @Override public boolean isRestrictingPermission(String permission) { if ( permission.equals(SecurityConstants.ADD_CHILDREN) || permission.equals(SecurityConstants.WRITE) || permission.equals(SecurityConstants.WRITE_PROPERTIES) || permission.equals(CustomSecurityConstants.CAN_ASK_FOR_PUBLISH) || permission.equals(SecurityConstants.REMOVE_CHILDREN) || permission.equals(SecurityConstants.REMOVE)) { return true; } return false; } @Override public Access checkPermission(Document doc, ACP mergedAcp, Principal principal, String permission, String[] resolvedPermissions, String[] additionalPrincipals) throws SecurityException { List<String> resolvedPermissionsList = Arrays.asList(resolvedPermissions); List<String> additionalPrincipalsList = Arrays.asList(additionalPrincipals); // Skip administrators and system if (additionalPrincipalsList.contains("administrators") || principal.equals("system")) { return Access.UNKNOWN; } if ("BROWSE".equals(permission)) { return Access.UNKNOWN; } String docType = doc.getType().getName(); String docTypeParent = null; if (doc.getParent() != null) { docTypeParent = doc.getParent().getType().getName(); } if ( hasPermissionInACP(mergedAcp, additionalPrincipalsList, CustomSecurityConstants.RECORD) ) { if (allowedDocumentTypes.isEmpty()) { allowedDocumentTypes.add("FVCategories"); allowedDocumentTypes.add("FVContributors"); allowedDocumentTypes.add("FVDictionary"); allowedDocumentTypes.add("FVResources"); } // Allow adding children and removing children on allowed types if (allowedDocumentTypes.contains(docType) && (resolvedPermissionsList.contains(SecurityConstants.ADD_CHILDREN) || resolvedPermissionsList.contains(SecurityConstants.REMOVE_CHILDREN)) ) { return Access.GRANT; } // Allow Publishing, Writing and Removing on allowed document type children if (docTypeParent != null && allowedDocumentTypes.contains(docTypeParent) && (resolvedPermissionsList.contains(SecurityConstants.WRITE_PROPERTIES) || resolvedPermissionsList.contains(SecurityConstants.REMOVE) || resolvedPermissionsList.contains(SecurityConstants.WRITE)) ) { return Access.GRANT; } } // Recorders can only publish to their allowed types (OK to use groups as this is globally applicable) if (additionalPrincipalsList.contains(CustomSecurityConstants.RECORDERS_GROUP) || additionalPrincipalsList.contains(CustomSecurityConstants.RECORDERS_APPROVERS_GROUP)) { if (!allowedDocumentTypes.contains(docType) && (resolvedPermissionsList.contains(CustomSecurityConstants.CAN_ASK_FOR_PUBLISH)) ) { return Access.DENY; } } return Access.UNKNOWN; } @Override public boolean isExpressibleInQuery(String repositoryName) { return false; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1248"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.xwiki.tool.spoon; import java.util.List; import java.util.Map; import org.apache.log4j.Level; import spoon.processing.AbstractProcessor; import spoon.processing.Property; import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtInvocation; /** * Failed the build if some code is calling a forbidden method. * * @version $Id$ * @since 9.9RC2 */ public class ForbiddenInvocationProcessor extends AbstractProcessor<CtInvocation<?>> { @Property private Map<String, List<String>> methods; @Override public void process(CtInvocation<?> element) { CtExpression<?> target = element.getTarget(); if (target != null && target.getType() != null) { String type = target.getType().getQualifiedName(); List<String> methodList = this.methods.get(type); if (methodList != null) { String method = element.getExecutable().getSimpleName(); if (methodList.contains(method)) { getFactory().getEnvironment().report(this, Level.ERROR, element, "Forbidden call to " + type + "#" + method); // Forcing the build to stop throw new RuntimeException("Forbidden call to " + type + "#" + method); } } } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1249"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.xwiki.test.ui.framework; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.events.EventFiringWebDriver; import org.xwiki.test.integration.XWikiExecutor; /** * This is a container for holding all of the information which should persist throughout all of the tests. * * @version $Id$ * @since 2.4M1 */ public class PersistentTestContext { /** This starts and stops the wiki engine. */ private final XWikiExecutor executor; private final WebDriver driver; /** Utility methods which should be available to tests and to pages. */ private final TestUtils util = new TestUtils(); public PersistentTestContext() throws Exception { this.executor = new XWikiExecutor(0); executor.start(); // Ensure that we display page source information if an HTML fails to be found, for easier debugging. this.driver = new EventFiringWebDriver(new FirefoxDriver()) { @Override public WebElement findElement(By by) { try { return super.findElement(by); } catch (NoSuchElementException e) { throw new NoSuchElementException(e.getMessage() + " Page source [" + getPageSource() + "]", e.getCause()); } } }; } public PersistentTestContext(PersistentTestContext toClone) { this.executor = toClone.executor; this.driver = toClone.driver; } public WebDriver getDriver() { return this.driver; } /** * @return Utility class with functions not specific to any test or element. */ public TestUtils getUtil() { return this.util; } public void shutdown() throws Exception { driver.close(); executor.stop(); } /** * Get a clone of this context which cannot be stopped by calling shutdown. this is needed so that individual tests * don't shutdown when AllTests ware being run. */ public PersistentTestContext getUnstoppable() { return new PersistentTestContext(this) { public void shutdown() { // Do nothing, that's why it's unstoppable. } }; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1250"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package io.github.lonamiwebs.stringlate.git; import android.app.Activity; import org.eclipse.jgit.lib.ProgressMonitor; import io.github.lonamiwebs.stringlate.R; import io.github.lonamiwebs.stringlate.interfaces.ProgressUpdateCallback; public abstract class GitCloneProgressCallback implements ProgressUpdateCallback, ProgressMonitor { private Activity mActivity; private int mCurrentTask, mDone, mWork; private long mLastMs; private final static long DELAY_PER_UPDATE = 60; // 60ms protected GitCloneProgressCallback(Activity activity) { mActivity = activity; } @Override final public void beginTask(String title, int totalWork) { mCurrentTask++; mLastMs = 0; mDone = 0; mWork = totalWork; } @Override final public void update(int completed) { mDone += completed; // This method is called way so often, slow it down long time = System.currentTimeMillis(); if (time - mLastMs >= DELAY_PER_UPDATE) { mLastMs = time; updateProgress(); } } @Override final public void start(int totalTasks) { /* Total tasks is a liar */ } @Override final public void endTask() { } private void updateProgress() { final String title = mActivity.getString(R.string.cloning_repo); final String content = mActivity.getString( R.string.cloning_repo_progress, getProgress(mCurrentTask, mDone, mWork)); // TODO This probably can be improved. Some handler to post the result? mActivity.runOnUiThread(new Runnable() { @Override public void run() { onProgressUpdate(title, content); } }); } private static float getProgress(int task, float done, float work) { // After timing cloning a large repository (F-Droid client) twice and averaging: if (work > 0 && task < 5) { return getTotalTime(task) + (done / work) * getTime(task); } else { return getTotalTime(task); } } private static float getTime(int task) { switch (task) { case 1: return 0.003f; case 2: return 0.204f; case 3: return 45.74f; case 4: return 54.52f; default: return 0.00f; } } private static float getTotalTime(int untilTask) { switch (untilTask) { case 1: return 0.000f; case 2: return 0.003f; case 3: return 0.207f; case 4: return 45.95f; default: return 1.00f; } } @Override final public boolean isCancelled() { return false; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1251"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package be.kuleuven.cs.distrinet.jnome.core.expression.invocation; import static be.kuleuven.cs.distrinet.rejuse.collection.CollectionOperations.exists; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.aikodi.chameleon.core.lookup.LookupException; import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage; import org.aikodi.chameleon.oo.type.Type; import org.aikodi.chameleon.oo.type.TypeInstantiation; import org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter; import org.aikodi.chameleon.oo.type.generics.EqualityConstraint; import org.aikodi.chameleon.oo.type.generics.EqualityTypeArgument; import org.aikodi.chameleon.oo.type.generics.ExtendsWildcard; import org.aikodi.chameleon.oo.type.generics.InstantiatedTypeParameter; import org.aikodi.chameleon.oo.type.generics.SuperWildcard; import org.aikodi.chameleon.oo.type.generics.TypeArgument; import org.aikodi.chameleon.oo.type.generics.TypeArgumentWithTypeReference; import org.aikodi.chameleon.oo.type.generics.TypeConstraint; import org.aikodi.chameleon.oo.type.generics.TypeParameter; import org.aikodi.chameleon.oo.type.generics.TypeVariable; import org.aikodi.chameleon.util.Util; import org.aikodi.chameleon.workspace.View; import be.kuleuven.cs.distrinet.jnome.core.language.Java7; import be.kuleuven.cs.distrinet.jnome.core.type.ArrayType; import be.kuleuven.cs.distrinet.jnome.core.type.ArrayTypeReference; import be.kuleuven.cs.distrinet.jnome.core.type.BasicJavaTypeReference; import be.kuleuven.cs.distrinet.jnome.core.type.JavaTypeReference; import be.kuleuven.cs.distrinet.rejuse.logic.ternary.Ternary; import be.kuleuven.cs.distrinet.rejuse.predicate.Predicate; /** * A = type() * F = typeReference() * * @author Marko van Dooren */ public abstract class FirstPhaseConstraint extends Constraint<FirstPhaseConstraint, FirstPhaseConstraintSet> { /** * * @param type * @param tref */ public FirstPhaseConstraint(JavaTypeReference A, Type F) { _A = A; _F = F; } private JavaTypeReference _A; public Type A() throws LookupException { return _A.getElement(); } public JavaTypeReference ARef() { return _A; } // private JavaTypeReference _typeReference; // public JavaTypeReference typeReference() { // return _typeReference; public Type F() { return _F; } private Type _F; public List<SecondPhaseConstraint> process() throws LookupException { List<SecondPhaseConstraint> result = new ArrayList<SecondPhaseConstraint>(); // If A is the type of null, no constraint is implied on Tj. Type A = A(); View view = A.view(); ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class); if(! A.equals(l.getNullType(view.namespace()))) { result.addAll(processFirstLevel()); } return result; } public List<SecondPhaseConstraint> processFirstLevel() throws LookupException { List<SecondPhaseConstraint> result = new ArrayList<SecondPhaseConstraint>(); // Declaration declarator = typeReference().getDeclarator(); if(F() instanceof TypeVariable && parent().typeParameters().contains(((TypeVariable)F()).parameter())) { // Otherwise, if F=Tj, then the constraint Tj :> A is implied. result.add(FequalsTj(((TypeVariable)F()).parameter(), ARef())); } else if(F() instanceof ArrayType) { // If F=U[], where the type U involves Tj, then if A is an array type V[], or // a type variable with an upper bound that is an array type V[], where V is a // reference type, this algorithm is applied recursively to the constraint V<<U if(A() instanceof ArrayType && involvesTypeParameter(F())) { Type componentType = ((ArrayType)A()).elementType(); if(componentType.is(language().REFERENCE_TYPE) == Ternary.TRUE) { JavaTypeReference componentTypeReference = ((ArrayTypeReference)Util.clone(ARef())).elementTypeReference(); componentTypeReference.setUniParent(ARef().parent()); FirstPhaseConstraint recursive = Array(componentTypeReference, ((ArrayType)F()).elementType()); result.addAll(recursive.process()); // FIXME: can't we unwrap the entire array dimension at once? This seems rather inefficient. } } } else if(A().is(language().PRIMITIVE_TYPE) != Ternary.TRUE){ // i is the index of the parameter we are processing. // V= the type reference of the i-th type parameter of some supertype G of A. List<TypeArgument> actualsOfF = new ArrayList<TypeArgument>(); for(TypeParameter par: F().parameters(TypeParameter.class)) { if(par instanceof InstantiatedTypeParameter) { actualsOfF.add(((InstantiatedTypeParameter)par).argument()); } else if(par instanceof CapturedTypeParameter) { List<TypeConstraint> constraints = ((CapturedTypeParameter) par).constraints(); if(constraints.size() == 1 && constraints.get(0) instanceof EqualityConstraint) { EqualityConstraint eq = (EqualityConstraint) constraints.get(0); EqualityTypeArgument arg = language().createEqualityTypeArgument(Util.clone(eq.typeReference())); arg.setUniParent(eq); actualsOfF.add(arg); } } } int i = 0; for(TypeArgument typeArgumentOfFormalParameter: actualsOfF) { if(typeArgumentOfFormalParameter instanceof EqualityTypeArgument) { JavaTypeReference U = (JavaTypeReference) ((EqualityTypeArgument)typeArgumentOfFormalParameter).typeReference(); if(involvesTypeParameter(U)) { caseSSFormalBasic(result, U, i); } } else if(typeArgumentOfFormalParameter instanceof ExtendsWildcard) { JavaTypeReference U = (JavaTypeReference) ((ExtendsWildcard)typeArgumentOfFormalParameter).typeReference(); if(involvesTypeParameter(U)) { caseSSFormalExtends(result, U, i); } } else if(typeArgumentOfFormalParameter instanceof SuperWildcard) { JavaTypeReference U = (JavaTypeReference) ((SuperWildcard)typeArgumentOfFormalParameter).typeReference(); if(involvesTypeParameter(U)) { caseSSFormalSuper(result, U, i); } } i++; } } // else { // result.addAll(processSpecifics()); return result; } public abstract void caseSSFormalBasic(List<SecondPhaseConstraint> result, JavaTypeReference U, int index) throws LookupException; public abstract void caseSSFormalExtends(List<SecondPhaseConstraint> result, JavaTypeReference U, int index) throws LookupException; public abstract void caseSSFormalSuper(List<SecondPhaseConstraint> result, JavaTypeReference U, int index) throws LookupException; public abstract SecondPhaseConstraint FequalsTj(TypeParameter declarator, JavaTypeReference type); public abstract FirstPhaseConstraint Array(JavaTypeReference componentType, Type componentTypeReference); // public abstract List<SecondPhaseConstraint> processSpecifics() throws LookupException; public boolean involvesTypeParameter(JavaTypeReference tref) throws LookupException { return ! involvedTypeParameters(tref).isEmpty(); } public boolean involvesTypeParameter(Type type) throws LookupException { return ((type instanceof TypeVariable) && (parent().typeParameters().contains(((TypeVariable) type).parameter()))) || ((type instanceof ArrayType) && (involvesTypeParameter(((ArrayType) type).elementType()))) || ((type instanceof TypeInstantiation) && (involvesTypeParameter(type.baseType()))) || exists(type.parameters(TypeParameter.class), object -> (object instanceof InstantiatedTypeParameter) && involvesTypeParameter(((InstantiatedTypeParameter) object).argument())); } public boolean involvesTypeParameter(TypeArgument arg) throws LookupException { return (arg instanceof TypeArgumentWithTypeReference) && involvesTypeParameter((JavaTypeReference) ((TypeArgumentWithTypeReference)arg).typeReference()); } public List<TypeParameter> involvedTypeParameters(JavaTypeReference tref) throws LookupException { Predicate<BasicJavaTypeReference, LookupException> predicate = object -> parent().typeParameters().contains(object.getDeclarator()); List<BasicJavaTypeReference> list = tref.descendants(BasicJavaTypeReference.class, predicate); if((tref instanceof BasicJavaTypeReference) && predicate.eval((BasicJavaTypeReference) tref)) { list.add((BasicJavaTypeReference) tref); } List<TypeParameter> parameters = new ArrayList<TypeParameter>(); for(BasicJavaTypeReference cref: list) { parameters.add((TypeParameter) cref.getDeclarator()); } return parameters; } public Java7 language() throws LookupException { return A().language(Java7.class); } public View view() throws LookupException { return A().view(); } protected Type typeWithSameBaseTypeAs(Type example, Collection<Type> toBeSearched) { Type baseType = example.baseType(); for(Type type:toBeSearched) { if(type.baseType().equals(baseType)) { return type; } } return null; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1252"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.rstudio.studio.client.workbench.prefs.views; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.ui.CheckBox; import com.google.inject.Inject; import org.rstudio.core.client.prefs.PreferencesDialogBaseResources; import org.rstudio.core.client.widget.NumericValueWidget; import org.rstudio.studio.client.workbench.prefs.model.RPrefs; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; public class EditingPreferencesPane extends PreferencesPane { @Inject public EditingPreferencesPane(UIPrefs prefs) { prefs_ = prefs; add(checkboxPref("Highlight selected word", prefs.highlightSelectedWord())); add(checkboxPref("Highlight selected line", prefs.highlightSelectedLine())); add(checkboxPref("Show line numbers", prefs.showLineNumbers())); add(tight(spacesForTab_ = checkboxPref("Insert spaces for tab", prefs.useSpacesForTab()))); add(indent(tabWidth_ = numericPref("Tab width", prefs.numSpacesForTab()))); add(tight(showMargin_ = checkboxPref("Show margin", prefs.showMargin()))); add(indent(marginCol_ = numericPref("Margin column", prefs.printMarginColumn()))); add(checkboxPref("Show whitespace characters", prefs_.showInvisibles())); add(checkboxPref("Show indent guides", prefs_.showIndentGuides())); add(checkboxPref("Blinking cursor", prefs_.blinkingCursor())); add(checkboxPref("Insert matching parens/quotes", prefs_.insertMatching())); add(checkboxPref("Auto-indent code after paste", prefs_.reindentOnPaste())); add(checkboxPref("Vertically align arguments in auto-indent", prefs_.verticallyAlignArgumentIndent())); add(checkboxPref("Soft-wrap R source files", prefs_.softWrapRFiles())); add(checkboxPref("Focus console after executing from source", prefs_.focusConsoleAfterExec())); add(checkboxPref("Show syntax highlighting in console input", prefs_.syntaxColorConsole())); add(checkboxPref("Enable vim editing mode", prefs_.useVimMode())); } @Override public ImageResource getIcon() { return PreferencesDialogBaseResources.INSTANCE.iconCodeEditing(); } @Override public boolean validate() { return (!spacesForTab_.getValue() || tabWidth_.validatePositive("Tab width")) && (!showMargin_.getValue() || marginCol_.validate("Margin column")); } @Override public String getName() { return "Code Editing"; } @Override protected void initialize(RPrefs prefs) { } private final UIPrefs prefs_; private final NumericValueWidget tabWidth_; private final NumericValueWidget marginCol_; private final CheckBox spacesForTab_; private final CheckBox showMargin_; }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1253"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.activiti.cycle.impl.connector.signavio.transform.pattern; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.activiti.cycle.RepositoryConnector; import org.activiti.cycle.impl.connector.signavio.SignavioPluginDefinition; import org.activiti.cycle.impl.connector.signavio.transform.JsonTransformationException; import org.oryxeditor.server.diagram.Diagram; import org.oryxeditor.server.diagram.DiagramBuilder; import org.oryxeditor.server.diagram.Shape; import org.oryxeditor.server.diagram.StencilType; /** * @author Falko Menge */ public class SubProcessExpansion extends OryxTransformation { public static final String STENCIL_SUBPROCESS = "Subprocess"; public static final String STENCIL_COLLAPSED_SUBPROCESS = "CollapsedSubprocess"; public static final String PROPERTY_NAME = "name"; public static final String PROPERTY_ENTRY = "entry"; public static final String PROPERTY_IS_CALL_ACTIVITY = "callacitivity"; private RepositoryConnector connector; public SubProcessExpansion(RepositoryConnector repositoryConnector) { this.connector = repositoryConnector; } @Override public Diagram transform(Diagram diagram) { expandSubProcesses(diagram); return diagram; } private void expandSubProcesses(Diagram diagram) { List<Shape> shapes = diagram.getShapes(); for (Shape shape : shapes) { if (STENCIL_COLLAPSED_SUBPROCESS.equals(shape.getStencilId()) && !"true".equals(shape.getProperty(PROPERTY_IS_CALL_ACTIVITY))) { String subProcessUrl = shape.getProperty(PROPERTY_ENTRY); if (subProcessUrl != null && subProcessUrl.length() > 0) { String subProcessName = shape.getProperty(PROPERTY_NAME); try { String subProcessId = getModelIdFromSignavioUrl(subProcessUrl); String representationName = SignavioPluginDefinition.CONTENT_REPRESENTATION_ID_JSON; String subProcessJson = connector.getContent(subProcessId, representationName).asString(); Diagram subProcess = DiagramBuilder.parseJson(subProcessJson); // FIXME subProcess = new ExtractProcessOfParticipant("Process Engine").transform(subProcess); expandSubProcesses(subProcess); shape.setStencil(new StencilType(STENCIL_SUBPROCESS)); ArrayList<Shape> childShapes = shape.getChildShapes(); childShapes.addAll(subProcess.getChildShapes()); } catch (Exception e) { throw new JsonTransformationException( "Error while retrieving Sub-Process" + " '" + subProcessName + "'" + " (URL: " + subProcessUrl + ").", e); } } } } } public static String getModelIdFromSignavioUrl(String subProcessUrl) throws UnsupportedEncodingException { String modelId = null; List<Pattern> patterns = new ArrayList<Pattern>(); patterns.add(Pattern.compile("^.*/p/model/(.*)$")); patterns.add(Pattern.compile("^.*/p/editor[?]id=(.*)$")); // workaround for Activiti Modeler for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(subProcessUrl); if (matcher.matches()) { modelId = URLDecoder.decode(matcher.group(1), "UTF-8"); break; } } return modelId; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1254"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.openhab.binding.zwave.internal; import java.math.BigDecimal; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.eclipse.smarthome.config.core.ConfigDescription; import org.eclipse.smarthome.config.core.ConfigDescriptionParameter; import org.eclipse.smarthome.config.core.ConfigDescriptionParameter.Type; import org.eclipse.smarthome.config.core.ConfigDescriptionParameterBuilder; import org.eclipse.smarthome.config.core.ConfigDescriptionParameterGroup; import org.eclipse.smarthome.config.core.ConfigDescriptionProvider; import org.eclipse.smarthome.config.core.ConfigDescriptionRegistry; import org.eclipse.smarthome.config.core.ConfigOptionProvider; import org.eclipse.smarthome.config.core.ParameterOption; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingRegistry; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.ThingUID; import org.eclipse.smarthome.core.thing.type.ThingType; import org.eclipse.smarthome.core.thing.type.ThingTypeRegistry; import org.openhab.binding.zwave.ZWaveBindingConstants; import org.openhab.binding.zwave.handler.ZWaveControllerHandler; import org.openhab.binding.zwave.internal.protocol.ZWaveNode; import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass; import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass.CommandClass; import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveUserCodeCommandClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableSet; public class ZWaveConfigProvider implements ConfigDescriptionProvider, ConfigOptionProvider { private final Logger logger = LoggerFactory.getLogger(ZWaveConfigProvider.class); private static ThingRegistry thingRegistry; private static ThingTypeRegistry thingTypeRegistry; private static ConfigDescriptionRegistry configDescriptionRegistry; private static Set<ThingTypeUID> zwaveThingTypeUIDList = new HashSet<ThingTypeUID>(); private static List<ZWaveProduct> productIndex = new ArrayList<ZWaveProduct>(); private static final Object productIndexLock = new Object(); // The following is a list of classes that are controllable. // This is used to filter endpoints so that when we display a list of nodes/endpoints // for configuring associations, we only list endpoints that are useful private static final Set<ZWaveCommandClass.CommandClass> controllableClasses = ImmutableSet.of(CommandClass.BASIC, CommandClass.SWITCH_BINARY, CommandClass.SWITCH_MULTILEVEL, CommandClass.SWITCH_TOGGLE_BINARY, CommandClass.SWITCH_TOGGLE_MULTILEVEL, CommandClass.CHIMNEY_FAN, CommandClass.THERMOSTAT_HEATING, CommandClass.THERMOSTAT_MODE, CommandClass.THERMOSTAT_OPERATING_STATE, CommandClass.THERMOSTAT_SETPOINT, CommandClass.THERMOSTAT_FAN_MODE, CommandClass.THERMOSTAT_FAN_STATE, CommandClass.FIBARO_FGRM_222); protected void setThingRegistry(ThingRegistry thingRegistry) { ZWaveConfigProvider.thingRegistry = thingRegistry; } protected void unsetThingRegistry(ThingRegistry thingRegistry) { ZWaveConfigProvider.thingRegistry = null; } protected void setThingTypeRegistry(ThingTypeRegistry thingTypeRegistry) { ZWaveConfigProvider.thingTypeRegistry = thingTypeRegistry; } protected void unsetThingTypeRegistry(ThingTypeRegistry thingTypeRegistry) { ZWaveConfigProvider.thingTypeRegistry = null; } protected void setConfigDescriptionRegistry(ConfigDescriptionRegistry configDescriptionRegistry) { ZWaveConfigProvider.configDescriptionRegistry = configDescriptionRegistry; } protected void unsetConfigDescriptionRegistry(ConfigDescriptionRegistry configDescriptionRegistry) { ZWaveConfigProvider.configDescriptionRegistry = null; } @Override public Collection<ConfigDescription> getConfigDescriptions(Locale locale) { logger.debug("getConfigDescriptions called"); return Collections.emptySet(); } @Override public ConfigDescription getConfigDescription(URI uri, Locale locale) { if (uri == null) { return null; } if ("thing".equals(uri.getScheme()) == false) { return null; } ThingUID thingUID = new ThingUID(uri.getSchemeSpecificPart()); ThingType thingType = thingTypeRegistry.getThingType(thingUID.getThingTypeUID()); if (thingType == null) { return null; } // Is this a zwave thing? if (!thingUID.getBindingId().equals(ZWaveBindingConstants.BINDING_ID)) { return null; } // And make sure this is a node because we want to get the id off the end... if (!thingUID.getId().startsWith("node")) { return null; } int nodeId = Integer.parseInt(thingUID.getId().substring(4)); Thing thing = getThing(thingUID); if (thing == null) { return null; } ThingUID bridgeUID = thing.getBridgeUID(); // Get the controller for this thing Thing bridge = getThing(bridgeUID); if (bridge == null) { return null; } // Get its handler and node ZWaveControllerHandler handler = (ZWaveControllerHandler) bridge.getHandler(); ZWaveNode node = handler.getNode(nodeId); List<ConfigDescriptionParameterGroup> groups = new ArrayList<ConfigDescriptionParameterGroup>(); List<ConfigDescriptionParameter> parameters = new ArrayList<ConfigDescriptionParameter>(); groups.add(new ConfigDescriptionParameterGroup("actions", "", false, "Actions", null)); groups.add(new ConfigDescriptionParameterGroup("thingcfg", "home", false, "Device Configuration", null)); parameters.add(ConfigDescriptionParameterBuilder .create(ZWaveBindingConstants.CONFIGURATION_POLLPERIOD, Type.INTEGER).withLabel("Polling Period") .withDescription("Set the minimum polling period for this device<BR/>" + "Note that the polling period may be longer than set since the binding treats " + "polls as the lowest priority data within the network.") .withDefault("1800").withMinimum(new BigDecimal(15)).withMaximum(new BigDecimal(7200)) .withGroupName("thingcfg").build()); // If we support the wakeup class, then add the configuration if (node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP) != null) { groups.add(new ConfigDescriptionParameterGroup("wakeup", "sleep", false, "Wakeup Configuration", null)); parameters.add(ConfigDescriptionParameterBuilder .create(ZWaveBindingConstants.CONFIGURATION_WAKEUPINTERVAL, Type.TEXT).withLabel("Wakeup Interval") .withDescription("Sets the number of seconds that the device will wakeup<BR/>" + "Setting a shorter time will allow openHAB to configure the device more regularly, but may use more battery power.<BR>" + "<B>Note:</B> This setting does not impact device notifications such as alarms.") .withDefault("").withGroupName("wakeup").build()); parameters.add( ConfigDescriptionParameterBuilder.create(ZWaveBindingConstants.CONFIGURATION_WAKEUPNODE, Type.TEXT) .withLabel("Wakeup Node").withAdvanced(true) .withDescription("Sets the wakeup node to which the device will send notifications.<BR/>" + "This should normally be set to the openHAB controller - " + "if it isn't, openHAB will not receive notifications when the device wakes up, " + "and will not be able to configure the device.") .withDefault("").withGroupName("wakeup").build()); } // If we support the node name class, then add the configuration if (node.getCommandClass(ZWaveCommandClass.CommandClass.NODE_NAMING) != null) { parameters.add( ConfigDescriptionParameterBuilder.create(ZWaveBindingConstants.CONFIGURATION_NODENAME, Type.TEXT) .withLabel("Node Name").withDescription("Sets a string for the device name") .withGroupName("thingcfg").withDefault("").build()); parameters.add(ConfigDescriptionParameterBuilder .create(ZWaveBindingConstants.CONFIGURATION_NODELOCATION, Type.TEXT) .withDescription("Sets a string for the device location").withLabel("Node Location").withDefault("") .withGroupName("thingcfg").build()); } // If we support the switch_all class, then add the configuration if (node.getCommandClass(ZWaveCommandClass.CommandClass.SWITCH_ALL) != null) { List<ParameterOption> options = new ArrayList<ParameterOption>(); options.add(new ParameterOption("0", "Exclude from All On and All Off groups")); options.add(new ParameterOption("1", "Include in All On group")); options.add(new ParameterOption("2", "Include in All Off group")); options.add(new ParameterOption("255", "Include in All On and All Off groups")); parameters.add(ConfigDescriptionParameterBuilder .create(ZWaveBindingConstants.CONFIGURATION_SWITCHALLMODE, Type.TEXT).withLabel("Switch All Mode") .withDescription("Set the mode for the switch when receiving SWITCH ALL commands.").withDefault("0") .withGroupName("thingcfg").withOptions(options).build()); } // If we support the powerlevel class, then add the configuration if (node.getCommandClass(ZWaveCommandClass.CommandClass.POWERLEVEL) != null) { List<ParameterOption> options = new ArrayList<ParameterOption>(); options.add(new ParameterOption("0", "Normal")); options.add(new ParameterOption("1", "Minus 1dB")); options.add(new ParameterOption("2", "Minus 2dB")); options.add(new ParameterOption("3", "Minus 3dB")); options.add(new ParameterOption("4", "Minus 4dB")); options.add(new ParameterOption("5", "Minus 5dB")); options.add(new ParameterOption("6", "Minus 6dB")); options.add(new ParameterOption("7", "Minus 7dB")); options.add(new ParameterOption("8", "Minus 8dB")); options.add(new ParameterOption("9", "Minus 9dB")); parameters.add(ConfigDescriptionParameterBuilder .create(ZWaveBindingConstants.CONFIGURATION_POWERLEVEL_LEVEL, Type.INTEGER).withLabel("Power Level") .withDescription( "Set the RF output level - Normal is maximum power<br>Setting the power to a lower level may be useful to reduce overloading of the receiver in adjacent nodes where they are close together, or if maximum power is not required for battery devices, it may extend battery life by reducing the transmit power.") .withDefault("0").withGroupName("thingcfg").withOptions(options).build()); parameters.add(ConfigDescriptionParameterBuilder .create(ZWaveBindingConstants.CONFIGURATION_POWERLEVEL_TIMEOUT, Type.INTEGER) .withLabel("Power Level Timeout") .withDescription( "Set the power level timeout in seconds<br>The node will reset to the normal power level if communications is not made within the specified number of seconds.") .withDefault("0").withGroupName("thingcfg").withOptions(options).build()); } // If we support DOOR_LOCK - add options if (node.getCommandClass(ZWaveCommandClass.CommandClass.DOOR_LOCK) != null) { parameters.add(ConfigDescriptionParameterBuilder .create(ZWaveBindingConstants.CONFIGURATION_DOORLOCKTIMEOUT, Type.TEXT).withLabel("Lock Timeout") .withDescription("Set the timeout on the lock.").withDefault("30").withGroupName("thingcfg") .build()); } ZWaveUserCodeCommandClass userCodeClass = (ZWaveUserCodeCommandClass) node .getCommandClass(ZWaveCommandClass.CommandClass.USER_CODE); if (userCodeClass != null && userCodeClass.getNumberOfSupportedCodes() > 0) { groups.add(new ConfigDescriptionParameterGroup("usercode", "lock", false, "User Code", null)); for (int code = 1; code <= userCodeClass.getNumberOfSupportedCodes(); code++) { parameters.add(ConfigDescriptionParameterBuilder .create(ZWaveBindingConstants.CONFIGURATION_USERCODE + code, Type.TEXT) .withLabel("Code " + code).withDescription("Set the user code (4 to 10 numbers)") .withDefault("").withGroupName("usercode").build()); } } List<ParameterOption> options = new ArrayList<ParameterOption>(); options.add(new ParameterOption(ZWaveBindingConstants.ACTION_CHECK_VALUE.toString(), "Do")); // If we're FAILED, allow removing from the controller // if (node.getNodeState() == ZWaveNodeState.FAILED) { parameters.add(ConfigDescriptionParameterBuilder.create("action_remove", Type.INTEGER) .withLabel("Remove device from controller").withAdvanced(true).withOptions(options) .withDefault("-232323").withGroupName("actions").build()); // } else { // Otherwise, allow us to put this on the failed list parameters.add(ConfigDescriptionParameterBuilder.create("action_failed", Type.INTEGER) .withLabel("Set device as FAILed").withAdvanced(true).withOptions(options).withDefault("-232323") .withGroupName("actions").build()); if (node.isInitializationComplete() == true) { parameters.add(ConfigDescriptionParameterBuilder.create("action_reinit", Type.INTEGER) .withLabel("Reinitialise the device").withAdvanced(true).withOptions(options).withDefault("-232323") .withGroupName("actions").build()); } parameters.add(ConfigDescriptionParameterBuilder.create("action_heal", Type.INTEGER) .withLabel("Heal the device").withAdvanced(true).withOptions(options).withDefault("-232323") .withGroupName("actions").build()); return new ConfigDescription(uri, parameters, groups); } private static void initialiseZWaveThings() { // Check that we know about the registry if (thingTypeRegistry == null) { return; } synchronized (productIndexLock) { zwaveThingTypeUIDList = new HashSet<ThingTypeUID>(); productIndex = new ArrayList<ZWaveProduct>(); // Get all the thing types Collection<ThingType> thingTypes = thingTypeRegistry.getThingTypes(); for (ThingType thingType : thingTypes) { // Is this for our binding? if (ZWaveBindingConstants.BINDING_ID.equals(thingType.getBindingId()) == false) { continue; } // Create a list of all things supported by this binding zwaveThingTypeUIDList.add(thingType.getUID()); // Get the properties Map<String, String> thingProperties = thingType.getProperties(); if (thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_REFERENCES) == null) { continue; } String[] references = thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_REFERENCES).split(","); for (String ref : references) { String[] values = ref.split(":"); Integer type; Integer id = null; if (values.length != 2) { continue; } type = Integer.parseInt(values[0], 16); if (!values[1].trim().equals("*")) { id = Integer.parseInt(values[1], 16); } String versionMin = thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_VERSIONMIN); String versionMax = thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_VERSIONMAX); productIndex.add(new ZWaveProduct(thingType.getUID(), Integer.parseInt(thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_MANUFACTURER), 16), type, id, versionMin, versionMax)); } } } } public static synchronized List<ZWaveProduct> getProductIndex() { // if (productIndex.size() == 0) { initialiseZWaveThings(); return productIndex; } public static Set<ThingTypeUID> getSupportedThingTypes() { // if (zwaveThingTypeUIDList.size() == 0) { initialiseZWaveThings(); return zwaveThingTypeUIDList; } public static ThingType getThingType(ThingTypeUID thingTypeUID) { // Check that we know about the registry if (thingTypeRegistry == null) { return null; } return thingTypeRegistry.getThingType(thingTypeUID); } public static ThingType getThingType(ZWaveNode node) { // Check that we know about the registry if (thingTypeRegistry == null) { return null; } for (ZWaveProduct product : ZWaveConfigProvider.getProductIndex()) { if (product.match(node) == true) { return thingTypeRegistry.getThingType(product.thingTypeUID); } } return null; } public static ConfigDescription getThingTypeConfig(ThingType type) { // Check that we know about the registry if (configDescriptionRegistry == null) { return null; } return configDescriptionRegistry.getConfigDescription(type.getConfigDescriptionURI()); } public static Thing getThing(ThingUID thingUID) { // Check that we know about the registry if (thingRegistry == null) { return null; } return thingRegistry.get(thingUID); } /** * Check if this node supports a controllable command class * * @param node the {@link ZWaveNode) * @return true if a controllable class is supported */ private boolean supportsControllableClass(ZWaveNode node) { for (CommandClass commandClass : controllableClasses) { if (node.supportsCommandClass(commandClass) == true) { return true; } } return false; } @Override public Collection<ParameterOption> getParameterOptions(URI uri, String param, Locale locale) { // We need to update the options of all requests for association groups... if (!"thing".equals(uri.getScheme())) { return null; } ThingUID thingUID = new ThingUID(uri.getSchemeSpecificPart()); ThingType thingType = thingTypeRegistry.getThingType(thingUID.getThingTypeUID()); if (thingType == null) { return null; } // Is this a zwave thing? if (!thingUID.getBindingId().equals(ZWaveBindingConstants.BINDING_ID)) { return null; } // And is it an association group? if (!param.startsWith("group_")) { return null; } // And make sure this is a node because we want to get the id off the end... if (!thingUID.getId().startsWith("node")) { return null; } int nodeId = Integer.parseInt(thingUID.getId().substring(4)); Thing thing = getThing(thingUID); ThingUID bridgeUID = thing.getBridgeUID(); // Get the controller for this thing Thing bridge = getThing(bridgeUID); if (bridge == null) { return null; } // Get its handler ZWaveControllerHandler handler = (ZWaveControllerHandler) bridge.getHandler(); boolean supportsMultiInstanceAssociation = false; ZWaveNode myNode = handler.getNode(nodeId); if (myNode.getCommandClass(CommandClass.MULTI_INSTANCE_ASSOCIATION) != null) { supportsMultiInstanceAssociation = true; } List<ParameterOption> options = new ArrayList<ParameterOption>(); // Add the controller (ie openHAB) to the top of the list options.add(new ParameterOption("node_" + handler.getOwnNodeId() + "_0", "openHAB Controller")); // And iterate over all its nodes Collection<ZWaveNode> nodes = handler.getNodes(); for (ZWaveNode node : nodes) { // Don't add its own id or the controller if (node.getNodeId() == nodeId || node.getNodeId() == handler.getOwnNodeId()) { continue; } // Get this nodes thing so we can find the name // TODO: Add this when thing names are supported! // Thing thingNode = getThing(thingUID); // Add the node for the standard association class if it supports a controllable class if (supportsControllableClass(node)) { // TODO: Use the node name options.add(new ParameterOption("node_" + node.getNodeId() + "_0", "Node " + node.getNodeId())); } // If the device supports multi_instance_association class, then add all controllable endpoints as well... // If this node also supports multi_instance class if (supportsMultiInstanceAssociation == true && node.getCommandClass(CommandClass.MULTI_INSTANCE) != null) { // Loop through all the endpoints for this device and add any that are controllable // for(node.get) // options.add(new ParameterOption("node" + node.getNodeId() + "." + endpointId, "Node " + // node.getNodeId())); } } return Collections.unmodifiableList(options); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1255"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package au.com.museumvictoria.fieldguide.vic.fork.ui.fragments; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import au.com.museumvictoria.fieldguide.vic.fork.R; import au.com.museumvictoria.fieldguide.vic.fork.adapter.SpeciesListCursorAdapter; import au.com.museumvictoria.fieldguide.vic.fork.db.FieldGuideDatabase; /** * A list of species in a group. This fragment also supports * tablet devices by allowing list items to be given an 'activated' state upon * selection. This helps indicate which item is currently being viewed in a * {@link SpeciesItemDetailFragment}. * * <p>Activities containing this fragment MUST implement the {@link Callbacks} * interface. */ public class GroupFragment extends Fragment { private static final String TAG = GroupFragment.class.getSimpleName(); private static final String ARGUMENT_GROUP_NAME = "speciesgroup"; /** * Callback interface to be notified when a species is selected. Activities using this fragment * must implement this interface. */ public interface Callback { void onSpeciesSelected(String speciesId, String name, @Nullable String subname); } private Callback callback; private SimpleAdapter sa; private ListView mListView; private Cursor mCursor; private FieldGuideDatabase fgdb; /** * TODO: Document exactly what groupName we expect. */ public static GroupFragment newInstance(String groupName) { Bundle arguments = new Bundle(); arguments.putString(ARGUMENT_GROUP_NAME, groupName); GroupFragment fragment = new GroupFragment(); fragment.setArguments(arguments); return fragment; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { callback = (Callback) activity; } catch (ClassCastException e) { throw new RuntimeException("Container activity does not implement callback."); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_group, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); fgdb = FieldGuideDatabase.getInstance(getActivity() .getApplicationContext()); mCursor = fgdb.getSpeciesInGroup(getArguments().getString(ARGUMENT_GROUP_NAME), SpeciesListCursorAdapter.getRequiredColumns()); mListView = (ListView) getView().findViewById(R.id.species_list); mListView.setFastScrollEnabled(true); final SpeciesListCursorAdapter adapter = new SpeciesListCursorAdapter(getActivity().getApplicationContext(), mCursor, 0); mListView.setAdapter(adapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i(TAG, "Click" + position + " " + id); // TODO: Need a better way to get IDs. callback.onSpeciesSelected(Long.toString(id), adapter.getLabelAtPosition(position), adapter.getSublabelAtPosition(position)); } }); } @Override public void onDestroy() { mCursor.close(); super.onDestroy(); } @Override public void onDetach() { callback = null; super.onDetach(); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1256"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.github.kaiwinter.androidremotenotifications.model; import com.github.kaiwinter.androidremotenotifications.RemoteNotifications; import java.util.Date; /** * Defines how often the notifications are updated from the server. Doing this on each start of your app ({@link #NOW}) * might lead to too many server calls. You can reduce them by using {@link #WEEKLY} or {@link #MONTHLY}. */ public enum UpdatePolicy { /** * The update is made now, regardless when the last one was. */ NOW(0), /** * The update is made once a week. {@link RemoteNotifications} uses an internal shared preference to track when the last update * was. */ WEEKLY(7 * 24 * 60 * 60 * 1000), /** * The update is made every second week. {@link RemoteNotifications} uses an internal shared preference to track when the last update * was. */ BI_WEEKLY(WEEKLY.getInterval() * 2), /** * The update is made once a month. {@link RemoteNotifications} uses an internal shared preference to track when the last * update was. */ MONTHLY(WEEKLY.getInterval() * 4); private final long interval; UpdatePolicy(long interval) { this.interval = interval; } private long getInterval() { return interval; } /** * Checks if the interval of this {@link UpdatePolicy} is over in regard to the <code>lastUpdate</code>. * * @param lastUpdate The {@link Date} of the last update. * @return <code>true</code> if an update should be done, else <code>false</code>. */ public boolean shouldUpdate(Date lastUpdate) { if (lastUpdate == null) { return true; } // be robust against small time differences when using NOW return System.currentTimeMillis() - interval >= lastUpdate.getTime(); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1257"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package edu.pitt.apollo; import edu.pitt.apollo.db.ApolloDatabaseKeyNotFoundException; import edu.pitt.apollo.db.ApolloDbUtils; import edu.pitt.apollo.service.translatorservice.v2_0_1.TranslatorServiceEI; import edu.pitt.apollo.types.v2_0_1.MethodCallStatusEnum; import edu.pitt.apollo.types.v2_0_1.RunAndSoftwareIdentification; import edu.pitt.apollo.types.v2_0_1.RunSimulationMessage; import edu.pitt.apollo.types.v2_0_1.ServiceRegistrationRecord; import edu.pitt.apollo.types.v2_0_1.SoftwareIdentification; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.sql.SQLException; import java.util.Map; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.transport.http.HTTPConduit; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; import edu.pitt.apollo.service.simulatorservice.v2_0_1.SimulatorServiceEI; import java.math.BigInteger; public class ApolloRunSimulationThread extends Thread { private ApolloDbUtils dbUtils; private RunSimulationMessage message; private int runId; private static ServiceRegistrationRecord translatorServiceRecord; private ApolloServiceImpl apolloServiceImpl; public ApolloRunSimulationThread(int runId, RunSimulationMessage message, ApolloDbUtils dbUtils, ApolloServiceImpl apolloServiceImpl) { System.out.println("in constructor"); this.message = message; this.runId = runId; this.dbUtils = dbUtils; this.apolloServiceImpl = apolloServiceImpl; } @Override public void run() { try { // first call the translator and translate the runSimulationMessage TranslatorServiceEI translatorPort; try { translatorPort = apolloServiceImpl.getTranslatorServicePort(new URL(translatorServiceRecord.getUrl())); } catch (MalformedURLException ex) { ErrorUtils.writeErrorToFile("MalformedURLEXception attempting to get the translator port for runId " + runId + ". URL was " + translatorServiceRecord.getUrl() + ". Error message was: " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId)); return; } // disable chunking for ZSI Client client = ClientProxy.getClient(translatorPort); HTTPConduit http = (HTTPConduit) client.getConduit(); HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); httpClientPolicy.setConnectionTimeout(36000); httpClientPolicy.setAllowChunking(false); http.setClient(httpClientPolicy); translatorPort.translateRunSimulationMessage(Integer.toString(runId), message); // while translator is running, query the status RunAndSoftwareIdentification translatorRasid = new RunAndSoftwareIdentification(); translatorRasid.setRunId(Integer.toString(runId)); translatorRasid.setSoftwareId(translatorServiceRecord.getSoftwareIdentification()); MethodCallStatusEnum status = MethodCallStatusEnum.QUEUED; // doesn't // really // matter try { while (!status.equals(MethodCallStatusEnum.TRANSLATION_COMPLETED)) { Thread.sleep(5000); status = apolloServiceImpl.getRunStatus(translatorRasid).getStatus(); if (status.equals(MethodCallStatusEnum.FAILED)) { ErrorUtils.writeErrorToFile("Translator service returned status of FAILED for runId " + runId, apolloServiceImpl.getErrorFile(runId)); return; } } } catch (InterruptedException ex) { ErrorUtils.writeErrorToFile("InterruptedException while attempting to get status of translator for runId " + runId + ": " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId)); } // once the translator has finished, call the simulator and start // the simulation SoftwareIdentification simulatorIdentification = message.getSimulatorIdentification(); String url = null; try { url = dbUtils.getUrlForSoftwareIdentification(simulatorIdentification); SimulatorServiceEI simulatorPort = apolloServiceImpl.getSimulatorServicePort(new URL(url)); // disable chunking for ZSI Client simulatorClient = ClientProxy.getClient(simulatorPort); HTTPConduit simulatorHttp = (HTTPConduit) simulatorClient.getConduit(); HTTPClientPolicy simulatorHttpClientPolicy = new HTTPClientPolicy(); simulatorHttpClientPolicy.setConnectionTimeout(36000); simulatorHttpClientPolicy.setAllowChunking(false); simulatorHttp.setClient(simulatorHttpClientPolicy); simulatorPort.runSimulation(new BigInteger(Integer.toString(runId)), message); } catch (ApolloDatabaseKeyNotFoundException ex) { ErrorUtils.writeErrorToFile( "Apollo database key not found attempting to get URL for simulator: " + simulatorIdentification.getSoftwareName() + ", version: " + simulatorIdentification.getSoftwareVersion() + ", developer: " + simulatorIdentification.getSoftwareDeveloper() + " for run id " + runId + ": " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId)); return; } catch (ClassNotFoundException ex) { ErrorUtils.writeErrorToFile( "ClassNotFoundException attempting to get URL for simulator: " + simulatorIdentification.getSoftwareName() + ", version: " + simulatorIdentification.getSoftwareVersion() + ", developer: " + simulatorIdentification.getSoftwareDeveloper() + " for run id " + runId + ": " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId)); return; } catch (MalformedURLException ex) { ErrorUtils.writeErrorToFile( "MalformedURLException attempting to create port for simulator: " + simulatorIdentification.getSoftwareName() + ", version: " + simulatorIdentification.getSoftwareVersion() + ", developer: " + simulatorIdentification.getSoftwareDeveloper() + " for run id " + runId + ". URL was: " + url + ". Error message was: " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId)); return; } catch (SQLException ex) { ErrorUtils.writeErrorToFile( "SQLException attempting to get URL for simulator: " + simulatorIdentification.getSoftwareName() + ", version: " + simulatorIdentification.getSoftwareVersion() + ", developer: " + simulatorIdentification.getSoftwareDeveloper() + " for run id " + runId + ": " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId)); return; } try { dbUtils.updateLastServiceToBeCalledForRun(runId, simulatorIdentification); } catch (ApolloDatabaseKeyNotFoundException ex) { ErrorUtils.writeErrorToFile("Apollo database key not found attempting to update last service" + " call for run id " + runId + ": " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId)); return; } catch (SQLException ex) { ErrorUtils.writeErrorToFile("SQLException attempting to update last service" + " call for run id " + runId + ": " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId)); return; } catch (ClassNotFoundException ex) { ErrorUtils.writeErrorToFile("ClassNotFoundException attempting to update last service" + " call for run id " + runId + ": " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId)); return; } } catch (IOException e) { System.out.println("Error writing error file!: " + e.getMessage()); } } public static void loadTranslatorSoftwareIdentification() { System.out.println("Loading translator software identification"); try { ApolloDbUtils dbUtils = new ApolloDbUtils(new File(ApolloServiceImpl.getDatabasePropertiesFilename())); Map<Integer, ServiceRegistrationRecord> softwareIdMap = dbUtils.getRegisteredSoftware(); for (Integer id : softwareIdMap.keySet()) { SoftwareIdentification softwareId = softwareIdMap.get(id).getSoftwareIdentification(); if (softwareId.getSoftwareName().toLowerCase().equals("translator")) { translatorServiceRecord = softwareIdMap.get(id); break; } } } catch (ClassNotFoundException ex) { throw new RuntimeException("ClassNotFoundException attempting to load the translator service record: " + ex.getMessage()); } catch (IOException ex) { throw new RuntimeException("IOException attempting to load the translator service record: " + ex.getMessage()); } catch (SQLException ex) { throw new RuntimeException("SQLException attempting to load the translator service record: " + ex.getMessage()); } if (translatorServiceRecord == null) { throw new RuntimeException("Could not find translator in the list of registered services"); } } // static { // try { // loadTranslatorSoftwareIdentification(); // } catch (ApolloRunSimulationException ex) { // throw new // RuntimeException("ApolloRunSimulationException attempting to load the translator service record: " // + ex.getMessage()); // } catch (ClassNotFoundException ex) { // throw new // RuntimeException("ClassNotFoundException attempting to load the translator service record: " // + ex.getMessage()); // } catch (IOException ex) { // throw new // RuntimeException("IOException attempting to load the translator service record: " // + ex.getMessage()); // } catch (SQLException ex) { // throw new // RuntimeException("SQLException attempting to load the translator service record: " // + ex.getMessage()); }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1258"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.axelor.apps.production.service.productionorder; import com.axelor.apps.base.db.Product; import com.axelor.apps.base.db.repo.SequenceRepository; import com.axelor.apps.base.service.administration.SequenceService; import com.axelor.apps.production.db.BillOfMaterial; import com.axelor.apps.production.db.ManufOrder; import com.axelor.apps.production.db.ProductionOrder; import com.axelor.apps.production.db.repo.ProductionOrderRepository; import com.axelor.apps.production.exceptions.IExceptionMessage; import com.axelor.apps.production.service.manuforder.ManufOrderService; import com.axelor.apps.sale.db.SaleOrder; import com.axelor.exception.AxelorException; import com.axelor.exception.db.repo.TraceBackRepository; import com.axelor.i18n.I18n; import com.google.inject.Inject; import com.google.inject.persist.Transactional; import java.lang.invoke.MethodHandles; import java.math.BigDecimal; import java.time.LocalDateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ProductionOrderServiceImpl implements ProductionOrderService { private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); protected ManufOrderService manufOrderService; protected SequenceService sequenceService; protected ProductionOrderRepository productionOrderRepo; @Inject public ProductionOrderServiceImpl( ManufOrderService manufOrderService, SequenceService sequenceService, ProductionOrderRepository productionOrderRepo) { this.manufOrderService = manufOrderService; this.sequenceService = sequenceService; this.productionOrderRepo = productionOrderRepo; } public ProductionOrder createProductionOrder(SaleOrder saleOrder) throws AxelorException { ProductionOrder productionOrder = new ProductionOrder(this.getProductionOrderSeq()); if (saleOrder != null) { productionOrder.setClientPartner(saleOrder.getClientPartner()); productionOrder.setSaleOrder(saleOrder); } return productionOrder; } public String getProductionOrderSeq() throws AxelorException { String seq = sequenceService.getSequenceNumber(SequenceRepository.PRODUCTION_ORDER); if (seq == null) { throw new AxelorException( TraceBackRepository.CATEGORY_CONFIGURATION_ERROR, I18n.get(IExceptionMessage.PRODUCTION_ORDER_SEQ)); } return seq; } /** * Generate a Production Order * * @param product Product must be passed in param because product can be different of bill of * material product (Product variant) * @param billOfMaterial * @param qtyRequested * @param businessProject * @return * @throws AxelorException */ @Transactional(rollbackOn = {Exception.class}) public ProductionOrder generateProductionOrder( Product product, BillOfMaterial billOfMaterial, BigDecimal qtyRequested, LocalDateTime startDate) throws AxelorException { ProductionOrder productionOrder = this.createProductionOrder(null); this.addManufOrder( productionOrder, product, billOfMaterial, qtyRequested, startDate, null, null, ManufOrderService.ORIGIN_TYPE_OTHER); return productionOrderRepo.save(productionOrder); } @Override @Transactional(rollbackOn = {Exception.class}) public ProductionOrder addManufOrder( ProductionOrder productionOrder, Product product, BillOfMaterial billOfMaterial, BigDecimal qtyRequested, LocalDateTime startDate, LocalDateTime endDate, SaleOrder saleOrder, int originType) throws AxelorException { ManufOrder manufOrder = manufOrderService.generateManufOrder( product, qtyRequested, ManufOrderService.DEFAULT_PRIORITY, ManufOrderService.IS_TO_INVOICE, billOfMaterial, startDate, endDate, originType); if (manufOrder != null) { if (saleOrder != null) { manufOrder.addSaleOrderSetItem(saleOrder); manufOrder.setClientPartner(saleOrder.getClientPartner()); manufOrder.setMoCommentFromSaleOrder(saleOrder.getProductionNote()); } productionOrder.addManufOrderSetItem(manufOrder); manufOrder.addProductionOrderSetItem(productionOrder); } return productionOrderRepo.save(productionOrder); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1259"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.grayben.riskExtractor.htmlScorer; import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.select.NodeVisitor; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; public class ScoringAndFlatteningNodeVisitor implements NodeVisitor { private Set<Scorer<Element>> elementScorers; private ScoredText flatText; public ScoredText getFlatText() { return flatText; } private Map<String, Integer> currentScores; public Map<String, Integer> getCurrentScores(){ return Collections.unmodifiableMap(currentScores); } private String currentString; private enum Operation { INCREMENT, DECREMENT } public ScoringAndFlatteningNodeVisitor(Set<Scorer<Element>> elementScorers) { super(); this.elementScorers = elementScorers; this.flatText = new ScoredText(); this.currentScores = new HashMap<>(); //initialise currentScores to DEFAULT_SCORE (probably 0) for (Scorer<Element> scorer: this.elementScorers){ currentScores.put(scorer.getScoreLabel(), scorer.DEFAULT_SCORE); } } @Override public void head(Node node, int depth) { validateInput(node, depth); if(! isElement(node)) return; Element element = (Element) node; processElement(element, Operation.INCREMENT); } @Override public void tail(Node node, int depth) { validateInput(node, depth); if (! isElement(node)) return; Element element = (Element) node; processElement(element, Operation.DECREMENT); } private void validateInput(Node node, int depth){ if (node == null) throw new NullPointerException( "Node was null" ); if (depth < 0) throw new IllegalArgumentException( "Depth was less than 0" ); } private boolean isElement(Node node){ if (node.getClass().equals(Element.class)) return true; else return false; } private void processElement(Element element, Operation operation){ this.currentString = element.ownText(); updateScores(element, operation); addScoredTextEntry(); } private void updateScores(Element element, Operation operation){ for (Scorer<Element> scorer : elementScorers) { assert this.currentScores.containsKey(scorer.getScoreLabel()); int currentScore = this.currentScores.get(scorer.getScoreLabel()); int elementScore = scorer.score(element); int newScore; switch (operation){ case INCREMENT: newScore = currentScore + elementScore; break; case DECREMENT: newScore = currentScore - elementScore; break; default: throw new IllegalArgumentException( "The operation specified is not supported" ); } this.currentScores.put(scorer.getScoreLabel(), newScore); } } private void addScoredTextEntry() { ScoredTextElement textElement = new ScoredTextElement( this.currentString, this.currentScores ); this.flatText.add(textElement); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1260"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.openhealthtools.mdht.uml.cda.core.util; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.Enumerator; import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.uml2.common.util.UML2Util; import org.eclipse.uml2.uml.Association; import org.eclipse.uml2.uml.Class; import org.eclipse.uml2.uml.Classifier; import org.eclipse.uml2.uml.Comment; import org.eclipse.uml2.uml.Constraint; import org.eclipse.uml2.uml.Element; import org.eclipse.uml2.uml.Enumeration; import org.eclipse.uml2.uml.EnumerationLiteral; import org.eclipse.uml2.uml.Generalization; import org.eclipse.uml2.uml.NamedElement; import org.eclipse.uml2.uml.OpaqueExpression; import org.eclipse.uml2.uml.Package; import org.eclipse.uml2.uml.Property; import org.eclipse.uml2.uml.Stereotype; import org.eclipse.uml2.uml.Type; import org.eclipse.uml2.uml.ValueSpecification; import org.eclipse.uml2.uml.util.UMLSwitch; import org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationship; import org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationshipKind; import org.openhealthtools.mdht.uml.cda.core.profile.Inline; import org.openhealthtools.mdht.uml.cda.core.profile.LogicalConstraint; import org.openhealthtools.mdht.uml.cda.core.profile.LogicalOperator; import org.openhealthtools.mdht.uml.cda.core.profile.SeverityKind; import org.openhealthtools.mdht.uml.cda.core.profile.Validation; import org.openhealthtools.mdht.uml.common.util.NamedElementUtil; import org.openhealthtools.mdht.uml.common.util.PropertyList; import org.openhealthtools.mdht.uml.common.util.UMLUtil; import org.openhealthtools.mdht.uml.term.core.profile.BindingKind; import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemConstraint; import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemVersion; import org.openhealthtools.mdht.uml.term.core.profile.ValueSetConstraint; import org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion; import org.openhealthtools.mdht.uml.term.core.util.ITermProfileConstants; import org.openhealthtools.mdht.uml.term.core.util.TermProfileUtil; public class CDAModelUtil { public static final String CDA_PACKAGE_NAME = "cda"; public static final String DATATYPES_NS_URI = "http: /** This base URL may be set from preferences or Ant task options. */ public static String INFOCENTER_URL = "http: public static final String SEVERITY_ERROR = "ERROR"; public static final String SEVERITY_WARNING = "WARNING"; public static final String SEVERITY_INFO = "INFO"; private static final String EPACKAGE = "Ecore::EPackage"; private static final String EREFERENCE = "Ecore::EReference"; public static final String XMLNAMESPACE = "xmlNamespace"; private static final String NSPREFIX = "nsPrefix"; private static final String NSURI = "nsURI"; // This message may change in the future to specify certain nullFlavor Types (such as the implementation, NI) private static final String NULLFLAVOR_SECTION_MESSAGE = "If section/@nullFlavor is not present, "; public static boolean cardinalityAfterElement = false; public static boolean disablePdfGeneration = false; public static boolean isAppendConformanceRules = false; public static Class getCDAClass(Classifier templateClass) { Class cdaClass = null; // if the provided class is from CDA and not a template if (isCDAModel(templateClass) && templateClass instanceof Class) { return (Class) templateClass; } for (Classifier parent : templateClass.allParents()) { // nearest package may be null if CDA model is not available if (parent.getNearestPackage() != null) { if (isCDAModel(parent) && parent instanceof Class) { cdaClass = (Class) parent; break; } } } return cdaClass; } public static Property getCDAProperty(Property templateProperty) { if (templateProperty.getClass_() == null) { return null; } // if the provided property is from a CDA class/datatype and not a template if (isCDAModel(templateProperty) || isDatatypeModel(templateProperty)) { return templateProperty; } for (Classifier parent : templateProperty.getClass_().allParents()) { for (Property inherited : parent.getAttributes()) { if (inherited.getName() != null && inherited.getName().equals(templateProperty.getName()) && (isCDAModel(inherited) || isDatatypeModel(inherited))) { return inherited; } } } return null; } /** * Returns the nearest inherited property with the same name, or null if not found. * * @deprecated Use the {@link UMLUtil#getInheritedProperty(Property)} API, instead. */ @Deprecated public static Property getInheritedProperty(Property templateProperty) { // for CDA, we restrict to Classes, not other classifiers if (templateProperty.getClass_() == null) { return null; } return UMLUtil.getInheritedProperty(templateProperty); } public static boolean isDatatypeModel(Element element) { if (element != null && element.getNearestPackage() != null) { Stereotype ePackage = element.getNearestPackage().getAppliedStereotype("Ecore::EPackage"); if (ePackage != null) { return DATATYPES_NS_URI.equals(element.getNearestPackage().getValue(ePackage, "nsURI")); } } return false; } /** * isCDAModel - use get top package to support nested uml packages within CDA model * primarily used for extensions * */ public static boolean isCDAModel(Element element) { if (element != null) { Package neareastPackage = element.getNearestPackage(); if (neareastPackage != null) { Package topPackage = org.openhealthtools.mdht.uml.common.util.UMLUtil.getTopPackage(neareastPackage); return CDA_PACKAGE_NAME.equals((topPackage != null) ? topPackage.getName() : ""); } } return false; } public static Class getCDADatatype(Classifier datatype) { Class result = null; // if the provided class is from CDA datatypes if (isDatatypeModel(datatype) && (datatype instanceof Class)) { result = (Class) datatype; } else { for (Classifier parent : datatype.allParents()) { // nearest package may be null if CDA datatypes model is not available if (parent.getNearestPackage() != null) { if (isDatatypeModel(parent) && (parent instanceof Class)) { result = (Class) parent; break; } } } } return result; } public static boolean isCDAType(Type templateClass, String typeName) { if (templateClass instanceof Class && typeName != null) { Class cdaClass = getCDAClass((Class) templateClass); if (cdaClass != null && typeName.equals(cdaClass.getName())) { return true; } } return false; } public static boolean isClinicalDocument(Type templateClass) { return isCDAType(templateClass, "ClinicalDocument"); } public static boolean isSection(Type templateClass) { return isCDAType(templateClass, "Section"); } public static boolean isOrganizer(Type templateClass) { return isCDAType(templateClass, "Organizer"); } public static boolean isEntry(Type templateClass) { return isCDAType(templateClass, "Entry"); } public static boolean isClinicalStatement(Type templateClass) { if (templateClass instanceof Class) { Class cdaClass = getCDAClass((Class) templateClass); String cdaName = cdaClass == null ? null : cdaClass.getName(); if (cdaClass != null && ("Act".equals(cdaName) || "Encounter".equals(cdaName) || "Observation".equals(cdaName) || "ObservationMedia".equals(cdaName) || "Organizer".equals(cdaName) || "Procedure".equals(cdaName) || "RegionOfInterest".equals(cdaName) || "SubstanceAdministration".equals(cdaName) || "Supply".equals(cdaName))) { return true; } } return false; } public static void composeAllConformanceMessages(Element element, final PrintStream stream, final boolean markup) { final TreeIterator<EObject> iterator = EcoreUtil.getAllContents(Collections.singletonList(element)); while (iterator != null && iterator.hasNext()) { EObject child = iterator.next(); UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() { @Override public Object caseAssociation(Association association) { iterator.prune(); return association; } @Override public Object caseClass(Class umlClass) { String message = computeConformanceMessage(umlClass, markup); stream.println(message); return umlClass; } @Override public Object caseGeneralization(Generalization generalization) { String message = computeConformanceMessage(generalization, markup); if (message.length() > 0) { stream.println(message); } return generalization; } @Override public Object caseProperty(Property property) { String message = computeConformanceMessage(property, markup); if (message.length() > 0) { stream.println(message); } return property; } @Override public Object caseConstraint(Constraint constraint) { String message = computeConformanceMessage(constraint, markup); if (message.length() > 0) { stream.println(message); } return constraint; } }; umlSwitch.doSwitch(child); } } public static String getValidationMessage(Element element) { return getValidationMessage(element, ICDAProfileConstants.VALIDATION); } /** * Obtains the user-specified validation message recorded in the given stereotype, or else * {@linkplain #computeConformanceMessage(Element, boolean) computes} a suitable conformance message if none. * * @param element * an element on which a validation constraint stereotype is defined * @param validationStereotypeName * the stereotype name (may be the abstract {@linkplain ICDAProfileConstants#VALIDATION Validation} stereotype) * * @return the most appropriate validation/conformance message * * @see #computeConformanceMessage(Element, boolean) */ public static String getValidationMessage(Element element, String validationStereotypeName) { String message = null; Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, validationStereotypeName); if (validationSupport != null) { message = (String) element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE); } if (message == null || message.length() == 0) { message = computeConformanceMessage(element, false); } return message; } public static String computeConformanceMessage(Element element, final boolean markup) { UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() { @Override public Object caseAssociation(Association association) { String message = null; Property property = getNavigableEnd(association); if (property != null) { message = computeConformanceMessage(property, false); } return message; } @Override public Object caseClass(Class umlClass) { return computeConformanceMessage(umlClass, markup); } @Override public Object caseGeneralization(Generalization generalization) { return computeConformanceMessage(generalization, markup); } @Override public Object caseProperty(Property property) { return computeConformanceMessage(property, markup); } @Override public Object caseConstraint(Constraint constraint) { return computeConformanceMessage(constraint, markup); } }; return (String) umlSwitch.doSwitch(element); } public static String computeConformanceMessage(Class template, final boolean markup) { String templateId = getTemplateId(template); String templateVersion = getTemplateVersion(template); String ruleIds = getConformanceRuleIds(template); if (templateId == null) { templateId = ""; } String templateMultiplicity = CDATemplateComputeBuilder.getMultiplicityRange(getMultiplicityRange(template)); final String templateIdAsBusinessName = "=\"" + templateId + "\""; final String templateVersionAsBusinessName = "=\"" + templateVersion + "\""; final String multiplicityRange = templateMultiplicity.isEmpty() ? "" : " [" + templateMultiplicity + "]"; CDATemplateComputeBuilder cdaTemplater = new CDATemplateComputeBuilder() { @Override public String addTemplateIdMultiplicity() { return multiplicityElementToggle(markup, "templateId", multiplicityRange, ""); } @Override public String addRootMultiplicity() { return multiplicityElementToggle(markup, "@root", " [1..1]", templateIdAsBusinessName); } @Override public String addTemplateVersion() { return multiplicityElementToggle(markup, "@extension", " [1..1]", templateVersionAsBusinessName); } }; return cdaTemplater.setRequireMarkup(markup).setRuleIds(ruleIds).setTemplateVersion( templateVersion).setMultiplicity(multiplicityRange).compute().toString(); } public static String computeConformanceMessage(Generalization generalization, boolean markup) { return computeConformanceMessage(generalization, markup, UMLUtil.getTopPackage(generalization)); } public static String computeConformanceMessage(Generalization generalization, boolean markup, Package xrefSource) { Class general = (Class) generalization.getGeneral(); StringBuffer message = new StringBuffer(computeGeneralizationConformanceMessage(general, markup, xrefSource)); appendConformanceRuleIds(generalization, message, markup); return message.toString(); } public static String computeGeneralizationConformanceMessage(Class general, boolean markup, Package xrefSource) { StringBuffer message = new StringBuffer(); String prefix = !UMLUtil.isSameModel(xrefSource, general) ? getModelPrefix(general) + " " : ""; String xref = computeXref(xrefSource, general); boolean showXref = markup && (xref != null); String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : ""; Class cdaGeneral = getCDAClass(general); if (cdaGeneral != null) { message.append(markup ? "<b>" : ""); message.append("SHALL"); message.append(markup ? "</b>" : ""); message.append(" conform to "); } else { message.append("Extends "); } message.append(showXref ? "<xref " + format + "href=\"" + xref + "\">" : ""); message.append(prefix).append(UMLUtil.splitName(general)); message.append(showXref ? "</xref>" : ""); String templateId = getTemplateId(general); String templateVersion = getTemplateVersion(general); if (templateId != null) { message.append(" template (templateId: "); message.append(markup ? "<tt>" : ""); message.append(templateId); // if there is an extension, add a colon followed by its value if (!StringUtils.isEmpty(templateVersion)) { message.append(":" + templateVersion); } message.append(markup ? "</tt>" : ""); message.append(")"); } return message.toString(); } private static String getBusinessName(NamedElement property) { String businessName = NamedElementUtil.getBusinessName(property); if (!property.getName().equals(businessName)) { return (" (" + businessName + ")"); } return ""; } private static StringBuffer multiplicityElementToggle(Property property, boolean markup, String elementName) { StringBuffer message = new StringBuffer(); message.append( multiplicityElementToggle(markup, elementName, getMultiplicityRange(property), getBusinessName(property))); return message; } private static String multiplicityElementToggle(boolean markup, String elementName, String multiplicityRange, String businessName) { StringBuffer message = new StringBuffer(); if (!cardinalityAfterElement) { message.append(multiplicityRange); } message.append(" "); message.append(markup ? "<tt><b>" : ""); message.append(elementName); message.append(markup ? "</b>" : ""); message.append(businessName); message.append(markup ? "</tt>" : ""); if (cardinalityAfterElement) { message.append(multiplicityRange); } return message.toString(); } public static String computeAssociationConformanceMessage(Property property, boolean markup, Package xrefSource, boolean appendNestedConformanceRules) { Class endType = (property.getType() instanceof Class) ? (Class) property.getType() : null; if (!isInlineClass(endType) && getTemplateId(property.getClass_()) != null) { return computeTemplateAssociationConformanceMessage( property, markup, xrefSource, appendNestedConformanceRules); } StringBuffer message = new StringBuffer(); Association association = property.getAssociation(); if (!markup) { message.append(getPrefixedSplitName(property.getClass_())).append(" "); } String keyword = getValidationKeywordWithPropertyRange(association, property); if (keyword != null) { message.append(markup ? "<b>" : ""); message.append(keyword); message.append(markup ? "</b>" : ""); message.append(" contain "); } else { if (property.getUpper() < 0 || property.getUpper() > 1) { message.append("contains "); } else { message.append("contain "); } } String elementName = getCDAElementName(property); message.append(getMultiplicityText(property)); message.append(multiplicityElementToggle(property, markup, elementName)); // appendSubsetsNotation(property, message, markup, xrefSource); if (appendNestedConformanceRules && endType != null) { if (markup && isInlineClass(endType) && !isPublishSeperately(endType)) { StringBuilder sb = new StringBuilder(); appendConformanceRuleIds(association, message, markup); appendPropertyComments(sb, property, markup); appendConformanceRules(sb, endType, (property.getUpper() == 1 ? "This " : "Such ") + (property.getUpper() == 1 ? elementName : NameUtilities.pluralize(elementName)) + " ", markup); message.append(" " + sb + " "); } else { message.append(", where its type is "); String prefix = !UMLUtil.isSameModel(xrefSource, endType) ? getModelPrefix(endType) + " " : ""; String xref = computeXref(xrefSource, endType); boolean showXref = markup && (xref != null); String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : ""; message.append(showXref ? "<xref " + format + "href=\"" + xref + "\">" : ""); message.append(prefix).append(UMLUtil.splitName(endType)); message.append(showXref ? "</xref>" : ""); appendConformanceRuleIds(association, message, markup); } } else { appendConformanceRuleIds(association, message, markup); } return message.toString(); } private static String computeTemplateAssociationConformanceMessage(Property property, boolean markup, Package xrefSource, boolean appendNestedConformanceRules) { StringBuffer message = new StringBuffer(); Association association = property.getAssociation(); String elementName = getCDAElementName(property); if (!markup) { message.append(getPrefixedSplitName(property.getClass_())).append(" "); } // errata 384 message support: if the class owner is a section, and it has an association // to either a clinical statement or an Entry (Act, Observation, etc.), append the message for (Property p : association.getMemberEnds()) { if ((p.getName() != null && !p.getName().isEmpty()) && (p.getOwner() != null && p.getType() != null) && (isSection((Class) p.getOwner()) && isClinicalStatement(p.getType()) || isEntry(p.getType()))) { message.append(NULLFLAVOR_SECTION_MESSAGE); } } String keyword = getValidationKeyword(association); if (keyword != null) { message.append(markup ? "<b>" : ""); message.append(keyword); message.append(markup ? "</b>" : ""); message.append(" contain "); } else { if (property.getUpper() < 0 || property.getUpper() > 1) { message.append("contains "); } else { message.append("contain "); } } message.append(multiplicityElementToggle(property, markup, elementName)); appendConformanceRuleIds(association, message, markup); if (appendNestedConformanceRules && property.getType() instanceof Class) { Class inlinedClass = (Class) property.getType(); if (markup && isInlineClass(inlinedClass)) { StringBuilder sb = new StringBuilder(); appendPropertyComments(sb, property, markup); appendConformanceRules(sb, inlinedClass, (property.getUpper() == 1 ? "This " : "Such ") + (property.getUpper() == 1 ? elementName : NameUtilities.pluralize(elementName)) + " ", markup); message.append(" " + sb); } } if (!markup) { String assocConstraints = computeAssociationConstraints(property, markup); if (assocConstraints.length() > 0) { message.append(assocConstraints); } } return message.toString(); } public static String computeAssociationConstraints(Property property, boolean markup) { StringBuffer message = new StringBuffer(); Association association = property.getAssociation(); Package xrefSource = UMLUtil.getTopPackage(property); EntryRelationship entryRelationship = CDAProfileUtil.getEntryRelationship(association); EntryRelationshipKind typeCode = entryRelationship != null ? entryRelationship.getTypeCode() : null; Class endType = (property.getType() instanceof Class) ? (Class) property.getType() : null; if (typeCode != null) { message.append(markup ? "\n<li>" : " "); message.append("Contains "); message.append(markup ? "<tt><b>" : "").append("@typeCode=\"").append( markup ? "</b>" : ""); message.append(typeCode).append("\" "); message.append(markup ? "</tt>" : ""); message.append(markup ? "<i>" : ""); message.append(typeCode.getLiteral()); message.append(markup ? "</i>" : ""); message.append(markup ? "</li>" : ", and"); } // TODO: what I should really do is test for an *implied* ActRelationship or Participation association if (endType != null && getCDAClass(endType) != null && !(isInlineClass(endType)) && !isInlineClass(property.getClass_())) { message.append(markup ? "\n<li>" : " "); message.append("Contains exactly one [1..1] "); String prefix = !UMLUtil.isSameModel(xrefSource, endType) ? getModelPrefix(endType) + " " : ""; String xref = computeXref(xrefSource, endType); boolean showXref = markup && (xref != null); String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : ""; message.append(showXref ? "<xref " + format + "href=\"" + xref + "\">" : ""); message.append(prefix).append(UMLUtil.splitName(endType)); message.append(showXref ? "</xref>" : ""); String templateId = getTemplateId(endType); String templateVersion = getTemplateVersion(endType); if (templateId != null) { message.append(" (templateId: "); message.append(markup ? "<tt>" : ""); message.append(templateId); // if there is an extension, add a colon followed by its value if (!StringUtils.isEmpty(templateVersion)) { message.append(":" + templateVersion); } message.append(markup ? "</tt>" : ""); message.append(")"); } message.append(markup ? "</li>" : ""); } return message.toString(); } public static String computeConformanceMessage(Property property, boolean markup) { return computeConformanceMessage(property, markup, UMLUtil.getTopPackage(property)); } private static String getNameSpacePrefix(Property property) { Property cdaBaseProperty = CDAModelUtil.getCDAProperty(property); String nameSpacePrefix = null; if (cdaBaseProperty != null) { Stereotype eReferenceStereoetype = cdaBaseProperty.getAppliedStereotype(CDAModelUtil.EREFERENCE); if (eReferenceStereoetype != null) { String nameSpace = (String) cdaBaseProperty.getValue(eReferenceStereoetype, CDAModelUtil.XMLNAMESPACE); if (!StringUtils.isEmpty(nameSpace)) { Package topPackage = org.openhealthtools.mdht.uml.common.util.UMLUtil.getTopPackage( cdaBaseProperty.getNearestPackage()); Stereotype ePackageStereoetype = topPackage.getApplicableStereotype(CDAModelUtil.EPACKAGE); if (ePackageStereoetype != null) { if (nameSpace.equals(topPackage.getValue(ePackageStereoetype, CDAModelUtil.NSURI))) { nameSpacePrefix = (String) topPackage.getValue(ePackageStereoetype, CDAModelUtil.NSPREFIX); } else { for (Package nestedPackage : topPackage.getNestedPackages()) { if (nameSpace.equals(nestedPackage.getValue(ePackageStereoetype, CDAModelUtil.NSURI))) { nameSpacePrefix = (String) nestedPackage.getValue( ePackageStereoetype, CDAModelUtil.NSPREFIX); } } } } } } } return nameSpacePrefix; } public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource) { return computeConformanceMessage(property, markup, xrefSource, true); } public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource, boolean appendNestedConformanceRules) { if (property.getType() == null) { System.out.println("Property has null type: " + property.getQualifiedName()); } if (property.getAssociation() != null && property.isNavigable()) { return computeAssociationConformanceMessage(property, markup, xrefSource, appendNestedConformanceRules); } StringBuffer message = new StringBuffer(); if (!markup) { message.append(getPrefixedSplitName(property.getClass_())).append(" "); } String keyword = getValidationKeywordWithPropertyRange(property); if (keyword != null) { message.append(markup ? "<b>" : ""); message.append(keyword); message.append(markup ? "</b>" : ""); message.append(" contain "); } else { if (property.getUpper() < 0 || property.getUpper() > 1) { message.append("contains "); } else { message.append("contain "); } } message.append(getMultiplicityText(property)); if (!cardinalityAfterElement) { message.append(getMultiplicityRange(property)); } message.append(" "); message.append(markup ? "<tt><b>" : ""); // classCode/moodCode if (isXMLAttribute(property)) { message.append("@"); } String propertyPrefix = getNameSpacePrefix(property); // Try to get CDA Name IExtensionRegistry reg = Platform.getExtensionRegistry(); IExtensionPoint ep = reg.getExtensionPoint("org.openhealthtools.mdht.uml.cda.core.TransformProvider"); IExtension[] extensions = ep.getExtensions(); TransformProvider newContributor = null; Property cdaProperty = null; try { newContributor = (TransformProvider) extensions[0].getConfigurationElements()[0].createExecutableExtension( "transform-class"); cdaProperty = newContributor.GetTransform(property); } catch (Exception e) { e.printStackTrace(); } String propertyCdaName = null; if (cdaProperty != null) { propertyCdaName = getCDAName(cdaProperty); } else { propertyCdaName = getCDAElementName(property); } message.append(propertyPrefix != null ? propertyPrefix + ":" + propertyCdaName : propertyCdaName); message.append(markup ? "</b>" : ""); message.append(getBusinessName(property)); if (property.getDefault() != null) { message.append("=\"").append(property.getDefault()).append("\" "); } message.append(markup ? "</tt>" : ""); if (cardinalityAfterElement) { message.append(getMultiplicityRange(property)); } Stereotype nullFlavorSpecification = CDAProfileUtil.getAppliedCDAStereotype( property, ICDAProfileConstants.NULL_FLAVOR); Stereotype textValue = CDAProfileUtil.getAppliedCDAStereotype(property, ICDAProfileConstants.TEXT_VALUE); if (nullFlavorSpecification != null) { String nullFlavor = getLiteralValue( property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR); Enumeration profileEnum = (Enumeration) nullFlavorSpecification.getProfile().getOwnedType( ICDAProfileConstants.NULL_FLAVOR_KIND); String nullFlavorLabel = getLiteralValueLabel( property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR, profileEnum); if (nullFlavor != null) { message.append(markup ? "<tt>" : ""); message.append("/@nullFlavor"); message.append(markup ? "</tt>" : ""); message.append(" = \"").append(nullFlavor).append("\" "); message.append(markup ? "<i>" : ""); message.append(nullFlavorLabel); message.append(markup ? "</i>" : ""); } } if (textValue != null) { String value = (String) property.getValue(textValue, ICDAProfileConstants.TEXT_VALUE_VALUE); if (value != null && value.length() > 0) { SeverityKind level = (SeverityKind) property.getValue( textValue, ICDAProfileConstants.VALIDATION_SEVERITY); message.append(" and ").append(markup ? "<b>" : "").append( level != null ? getValidationKeyword(level.getLiteral()) : keyword).append( markup ? "</b>" : "").append(" equal \"").append(value).append("\""); } } /* * Append datatype restriction, if redefined to a specialized type */ List<Property> redefinedProperties = UMLUtil.getRedefinedProperties(property); Property redefinedProperty = redefinedProperties.isEmpty() ? null : redefinedProperties.get(0); if (property.getType() != null && ((redefinedProperty == null || (!isXMLAttribute(property) && (property.getType() != redefinedProperty.getType()))))) { message.append(" with " + "@xsi:type=\""); if (redefinedProperty != null && redefinedProperty.getType() != null && redefinedProperty.getType().getName() != null && !redefinedProperty.getType().getName().isEmpty()) { message.append(redefinedProperty.getType().getName()); } else { message.append(property.getType().getName()); } message.append("\""); } // for vocab properties, put rule ID at end, use terminology constraint if specified if (isHL7VocabAttribute(property)) { String ruleIds = getTerminologyConformanceRuleIds(property); // if there are terminology rule IDs, then include property rule IDs here if (ruleIds.length() > 0) { appendConformanceRuleIds(property, message, markup); } } else { // PropertyConstraint stereotype ruleIds, if specified appendConformanceRuleIds(property, message, markup); } Stereotype codeSystemConstraint = TermProfileUtil.getAppliedStereotype( property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT); Stereotype valueSetConstraint = TermProfileUtil.getAppliedStereotype( property, ITermProfileConstants.VALUE_SET_CONSTRAINT); if (codeSystemConstraint != null) { String vocab = computeCodeSystemMessage(property, markup); message.append(vocab); } else if (valueSetConstraint != null) { String vocab = computeValueSetMessage(property, markup, xrefSource); message.append(vocab); } else if (isHL7VocabAttribute(property) && property.getDefault() != null) { String vocab = computeHL7VocabAttributeMessage(property, markup); message.append(vocab); } // for vocab properties, put rule ID at end, use terminology constraint if specified if (isHL7VocabAttribute(property)) { String ruleIds = getTerminologyConformanceRuleIds(property); if (ruleIds.length() > 0) { appendTerminologyConformanceRuleIds(property, message, markup); } else { appendConformanceRuleIds(property, message, markup); } } else { // rule IDs for the terminology constraint appendTerminologyConformanceRuleIds(property, message, markup); } if (property.getType() != null && appendNestedConformanceRules && property.getType() instanceof Class) { if (isInlineClass((Class) property.getType())) { if (isPublishSeperately((Class) property.getType())) { String xref = (property.getType() instanceof Classifier && UMLUtil.isSameProject(property, property.getType())) ? computeXref(xrefSource, (Classifier) property.getType()) : null; boolean showXref = markup && (xref != null); if (showXref) { String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : ""; message.append(showXref ? "<xref " + format + "href=\"" + xref + "\">" : ""); message.append(UMLUtil.splitName(property.getType())); message.append(showXref ? "</xref>" : ""); } } else { StringBuilder sb = new StringBuilder(); boolean hadSideEffect = appendPropertyComments(sb, property, markup); if (isAppendConformanceRules) { int len = sb.length(); appendConformanceRules(sb, (Class) property.getType(), "", markup); hadSideEffect |= sb.length() > len; } if (hadSideEffect) { message.append(" " + sb); } } } } return message.toString(); } /** * getCDAName * * recursively, depth first, check the object graph for a CDA Name using the root of the "redefined" * property if it exists. * * Also handle special cases like sectionId which has a cdaName of ID * * @param cdaProperty * an MDHT property * @return string * the calculated CDA name */ private static String getCDAName(Property cdaProperty) { EList<Property> redefines = cdaProperty.getRedefinedProperties(); // if there is a stereotype name, use it String name = getStereotypeName(cdaProperty); if (name != null) { return name; } // if there are redefines, check for more but only along the first branch (0) if (redefines != null && redefines.size() > 0) { return getCDAName(redefines.get(0)); } // eventually return the property Name of the root redefined element; return cdaProperty.getName(); } /** * Get the CDA name from a stereotype if it exists * * @param cdaProperty * a Property * @return the xmlName or null if no stereotype exists */ private static String getStereotypeName(Property cdaProperty) { Stereotype eAttribute = cdaProperty.getAppliedStereotype("Ecore::EAttribute"); String name = null; if (eAttribute != null) { name = (String) cdaProperty.getValue(eAttribute, "xmlName"); } return name; } private static void appendSubsetsNotation(Property property, StringBuffer message, boolean markup, Package xrefSource) { StringBuffer notation = new StringBuffer(); for (Property subsets : property.getSubsettedProperties()) { if (subsets.getClass_() == null) { // eliminate NPE when publishing stereotype references to UML metamodel continue; } if (notation.length() == 0) { notation.append(" {subsets "); } else { notation.append(", "); } String xref = computeXref(xrefSource, subsets.getClass_()); boolean showXref = markup && (xref != null); String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : ""; notation.append(showXref ? " <xref " + format + "href=\"" + xref + "\">" : " "); notation.append(UMLUtil.splitName(subsets.getClass_())); notation.append(showXref ? "</xref>" : ""); notation.append("::" + subsets.getName()); } if (notation.length() > 0) { notation.append("}"); } message.append(notation); } private static final String[] OL = { "<ol>", "</ol>" }; private static final String[] LI = { "<li>", "</li>" }; private static final String[] NOOL = { "", " " }; private static final String[] NOLI = { "", " " }; static private void appendConformanceRules(StringBuilder appendB, Class umlClass, String prefix, boolean markup) { String[] ol = markup ? OL : NOOL; String[] li = markup ? LI : NOLI; StringBuilder sb = new StringBuilder(); boolean hasRules = false; if (!CDAModelUtil.isInlineClass(umlClass)) { for (Generalization generalization : umlClass.getGeneralizations()) { Classifier general = generalization.getGeneral(); if (!RIMModelUtil.isRIMModel(general) && !CDAModelUtil.isCDAModel(general)) { String message = CDAModelUtil.computeConformanceMessage(generalization, markup); if (message.length() > 0) { hasRules = true; sb.append(li[0] + prefix + message + li[1]); } } } } // categorize constraints by constrainedElement name List<Constraint> unprocessedConstraints = new ArrayList<Constraint>(); // propertyName -> constraints Map<String, List<Constraint>> constraintMap = new HashMap<String, List<Constraint>>(); // constraint -> sub-constraints Map<Constraint, List<Constraint>> subConstraintMap = new HashMap<Constraint, List<Constraint>>(); for (Constraint constraint : umlClass.getOwnedRules()) { unprocessedConstraints.add(constraint); // Do not associate logical constraints with a property because they are a class and not a property constraint if (CDAProfileUtil.getLogicalConstraint(constraint) == null) { for (Element element : constraint.getConstrainedElements()) { if (element instanceof Property) { String name = ((Property) element).getName(); List<Constraint> rules = constraintMap.get(name); if (rules == null) { rules = new ArrayList<Constraint>(); constraintMap.put(name, rules); } rules.add(constraint); } else if (element instanceof Constraint) { Constraint subConstraint = (Constraint) element; List<Constraint> rules = subConstraintMap.get(subConstraint); if (rules == null) { rules = new ArrayList<Constraint>(); subConstraintMap.put(subConstraint, rules); } rules.add(constraint); } } } } PropertyList propertyList = new PropertyList(umlClass, CDAModelUtil.isInlineClass(umlClass)); // XML attributes for (Property property : propertyList.getAttributes()) { hasRules = hasRules | appendPropertyList( umlClass, property, markup, ol, sb, prefix, li, constraintMap, unprocessedConstraints, subConstraintMap); } // XML elements for (Property property : propertyList.getAssociationEnds()) { hasRules = hasRules | appendPropertyList( umlClass, property, markup, ol, sb, prefix, li, constraintMap, unprocessedConstraints, subConstraintMap); } for (Constraint constraint : unprocessedConstraints) { hasRules = true; sb.append(li[0] + prefix + CDAModelUtil.computeConformanceMessage(constraint, markup) + li[1]); } if (hasRules) { appendB.append(ol[0]); appendB.append(sb); appendB.append(ol[1]); } } private static boolean appendPropertyList(Element umlClass, Property property, boolean markup, String[] ol, StringBuilder sb, String prefix, String[] li, Map<String, List<Constraint>> constraintMap, List<Constraint> unprocessedConstraints, Map<Constraint, List<Constraint>> subConstraintMap) { boolean result = false; if (!CDAModelUtil.isCDAModel(umlClass) && !CDAModelUtil.isCDAModel(property) && !CDAModelUtil.isDatatypeModel(property)) { result = true; String ccm = CDAModelUtil.computeConformanceMessage(property, markup); boolean order = ccm.trim().endsWith(ol[1]); boolean currentlyItem = false; if (order) { int olIndex = ccm.lastIndexOf(ol[1]); ccm = ccm.substring(0, olIndex); currentlyItem = ccm.trim().endsWith(li[1]); } sb.append(li[0] + prefix + ccm); StringBuilder propertyComments = new StringBuilder(); currentlyItem &= appendPropertyComments(propertyComments, property, markup); if (currentlyItem) { sb.append(li[0]).append(propertyComments).append(li[1]); } appendPropertyRules(sb, property, constraintMap, subConstraintMap, unprocessedConstraints, markup, !order); if (order) { sb.append(ol[1]); } sb.append(li[1]); } return result; } private static boolean appendPropertyComments(StringBuilder sb, Property property, boolean markup) { // INLINE Association association = property.getAssociation(); int startingStrLength = sb.length(); if (association != null && association.getOwnedComments().size() > 0) { if (markup) { sb.append("<p><lines><i>"); } for (Comment comment : association.getOwnedComments()) { sb.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody())); } if (markup) { sb.append("</i></lines></p>"); } } if (property.getOwnedComments().size() > 0) { if (markup) { sb.append("<p><lines><i>"); } for (Comment comment : property.getOwnedComments()) { sb.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody())); } if (markup) { sb.append("</i></lines></p>"); } } return sb.length() > startingStrLength; } private static void appendPropertyRules(StringBuilder sb, Property property, Map<String, List<Constraint>> constraintMap, Map<Constraint, List<Constraint>> subConstraintMap, List<Constraint> unprocessedConstraints, boolean markup, boolean newOrder) { String[] ol = markup && newOrder ? OL : NOOL; String[] li = markup ? LI : NOLI; // association typeCode and property type String assocConstraints = ""; if (property.getAssociation() != null) { assocConstraints = CDAModelUtil.computeAssociationConstraints(property, markup); } StringBuffer ruleConstraints = new StringBuffer(); List<Constraint> rules = constraintMap.get(property.getName()); if (rules != null && !rules.isEmpty()) { for (Constraint constraint : rules) { unprocessedConstraints.remove(constraint); ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(constraint, markup)); appendSubConstraintRules(ruleConstraints, constraint, subConstraintMap, unprocessedConstraints, markup); ruleConstraints.append(li[1]); } } if (assocConstraints.length() > 0 || ruleConstraints.length() > 0) { sb.append(ol[0]); sb.append(assocConstraints); sb.append(ruleConstraints); sb.append(ol[1]); } } private static void appendSubConstraintRules(StringBuffer ruleConstraints, Constraint constraint, Map<Constraint, List<Constraint>> subConstraintMap, List<Constraint> unprocessedConstraints, boolean markup) { String[] ol; String[] li; if (markup) { ol = OL; li = LI; } else { ol = NOOL; li = NOLI; } List<Constraint> subConstraints = subConstraintMap.get(constraint); if (subConstraints != null && subConstraints.size() > 0) { ruleConstraints.append(ol[0]); for (Constraint subConstraint : subConstraints) { unprocessedConstraints.remove(subConstraint); ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(subConstraint, markup)); appendSubConstraintRules( ruleConstraints, subConstraint, subConstraintMap, unprocessedConstraints, markup); ruleConstraints.append(li[1]); } ruleConstraints.append(ol[1]); } } private static boolean isHL7VocabAttribute(Property property) { String name = property.getName(); return "classCode".equals(name) || "moodCode".equals(name) || "typeCode".equals(name); } private static String computeHL7VocabAttributeMessage(Property property, boolean markup) { StringBuffer message = new StringBuffer(); Class rimClass = RIMModelUtil.getRIMClass(property.getClass_()); String code = property.getDefault(); String displayName = null; String codeSystemId = null; String codeSystemName = null; if (rimClass != null) { if ("Act".equals(rimClass.getName())) { if ("classCode".equals(property.getName())) { codeSystemName = "HL7ActClass"; codeSystemId = "2.16.840.1.113883.5.6"; if ("ACT".equals(code)) { displayName = "Act"; } else if ("OBS".equals(code)) { displayName = "Observation"; } } else if ("moodCode".equals(property.getName())) { codeSystemName = "HL7ActMood"; codeSystemId = "2.16.840.1.113883.5.1001"; if ("EVN".equals(code)) { displayName = "Event"; } } } } if (displayName != null) { message.append(markup ? "<i>" : ""); message.append(displayName); message.append(markup ? "</i>" : ""); } if (codeSystemId != null || codeSystemName != null) { message.append(" (CodeSystem:"); message.append(markup ? "<tt>" : ""); if (codeSystemId != null) { message.append(" ").append(codeSystemId); } if (codeSystemName != null) { message.append(" ").append(codeSystemName); } message.append(markup ? "</tt>" : ""); message.append(")"); } return message.toString(); } private static String computeCodeSystemMessage(Property property, boolean markup) { Stereotype codeSystemConstraintStereotype = TermProfileUtil.getAppliedStereotype( property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT); CodeSystemConstraint codeSystemConstraint = TermProfileUtil.getCodeSystemConstraint(property); String keyword = getValidationKeyword(property, codeSystemConstraintStereotype); String id = null; String name = null; String code = null; String displayName = null; if (codeSystemConstraint != null) { if (codeSystemConstraint.getReference() != null) { CodeSystemVersion codeSystemVersion = codeSystemConstraint.getReference(); id = codeSystemVersion.getIdentifier(); name = codeSystemVersion.getEnumerationName(); codeSystemVersion.getVersion(); } else { id = codeSystemConstraint.getIdentifier(); name = codeSystemConstraint.getName(); codeSystemConstraint.getVersion(); } codeSystemConstraint.getBinding(); code = codeSystemConstraint.getCode(); displayName = codeSystemConstraint.getDisplayName(); } StringBuffer message = new StringBuffer(); if (code != null) { message.append(markup ? "<tt><b>" : ""); // single value binding message.append("/@code"); message.append(markup ? "</b>" : ""); message.append("=\"").append(code).append("\" "); message.append(markup ? "</tt>" : ""); if (displayName != null) { message.append(markup ? "<i>" : ""); message.append(displayName); message.append(markup ? "</i>" : ""); } } else { // capture and return proper xml binding message based on mandatory or not message.append(mandatoryOrNotMessage(property)); if (keyword != null) { message.append(markup ? "<b>" : ""); message.append(keyword); message.append(markup ? "</b>" : ""); message.append(" be"); } else { message.append("is"); } message.append(" selected from"); } if (id != null || name != null) { message.append(" (CodeSystem:"); message.append(markup ? "<tt>" : ""); if (id != null) { message.append(" ").append(id); } if (name != null) { message.append(" ").append(name); } message.append(markup ? "</tt>" : ""); message.append(")"); } return message.toString(); } private static String computeValueSetMessage(Property property, boolean markup, Package xrefSource) { Stereotype valueSetConstraintStereotype = TermProfileUtil.getAppliedStereotype( property, ITermProfileConstants.VALUE_SET_CONSTRAINT); ValueSetConstraint valueSetConstraint = TermProfileUtil.getValueSetConstraint(property); String keyword = getValidationKeyword(property, valueSetConstraintStereotype); String id = null; String name = null; String version = null; BindingKind binding = null; String xref = null; String xrefFormat = ""; boolean showXref = false; if (valueSetConstraint != null) { if (valueSetConstraint.getReference() != null) { ValueSetVersion valueSetVersion = valueSetConstraint.getReference(); id = valueSetVersion.getIdentifier(); name = valueSetVersion.getEnumerationName(); version = valueSetVersion.getVersion(); binding = valueSetVersion.getBinding(); if (valueSetVersion.getBase_Enumeration() != null) { xref = computeTerminologyXref(property.getClass_(), valueSetVersion.getBase_Enumeration()); } showXref = markup && (xref != null); xrefFormat = showXref && xref.endsWith(".html") ? "format=\"html\" " : ""; } else { id = valueSetConstraint.getIdentifier(); name = valueSetConstraint.getName(); version = valueSetConstraint.getVersion(); binding = valueSetConstraint.getBinding(); } } StringBuffer message = new StringBuffer(); // capture and return proper xml binding message based on mandatory or not message.append(mandatoryOrNotMessage(property)); if (keyword != null) { message.append(markup ? "<b>" : ""); message.append(keyword); message.append(markup ? "</b>" : ""); message.append(" be"); } else { message.append("is"); } message.append(" selected from ValueSet"); message.append(markup ? "<tt>" : ""); if (name != null) { message.append(" "); message.append(showXref ? "<xref " + xrefFormat + "href=\"" + xref + "\">" : ""); message.append(name); message.append(showXref ? "</xref>" : ""); } if (id != null) { message.append(" ").append(id); } message.append(markup ? "</tt>" : ""); message.append(markup ? "<b>" : ""); message.append(" ").append(binding.getName().toUpperCase()); message.append(markup ? "</b>" : ""); if (BindingKind.STATIC == binding && version != null) { message.append(" ").append(version); } return message.toString(); } public static String computeConformanceMessage(Constraint constraint, boolean markup) { LogicalConstraint logicConstraint = CDAProfileUtil.getLogicalConstraint(constraint); if (logicConstraint != null) { return computeLogicalConformanceMessage(constraint, logicConstraint, markup); } else { return computeCustomConformanceMessage(constraint, markup); } } private static String computeCustomConformanceMessage(Constraint constraint, boolean markup) { StringBuffer message = new StringBuffer(); String strucTextBody = null; String analysisBody = null; Map<String, String> langBodyMap = new HashMap<String, String>(); CDAProfileUtil.getLogicalConstraint(constraint); ValueSpecification spec = constraint.getSpecification(); if (spec instanceof OpaqueExpression) { for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) { String lang = ((OpaqueExpression) spec).getLanguages().get(i); String body = ((OpaqueExpression) spec).getBodies().get(i); if ("StrucText".equals(lang)) { strucTextBody = body; } else if ("Analysis".equals(lang)) { analysisBody = body; } else { langBodyMap.put(lang, body); } } } String displayBody = null; if (strucTextBody != null && strucTextBody.trim().length() > 0) { // TODO if markup, parse strucTextBody and insert DITA markup displayBody = strucTextBody; } else if (analysisBody != null && analysisBody.trim().length() > 0) { Boolean ditaEnabled = false; try { Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype( constraint, ICDAProfileConstants.CONSTRAINT_VALIDATION); ditaEnabled = (Boolean) constraint.getValue(stereotype, ICDAProfileConstants.CONSTRAINT_DITA_ENABLED); } catch (IllegalArgumentException e) { /* Swallow this */ } if (markup && !ditaEnabled) { // escape non-dita markup in analysis text displayBody = escapeMarkupCharacters(analysisBody); // change severity words to bold text displayBody = replaceSeverityWithBold(displayBody); } else { displayBody = analysisBody; } } if (displayBody == null) { List<Stereotype> stereotypes = constraint.getAppliedStereotypes(); if (stereotypes.isEmpty()) { // This should never happen but in case it does we deal with it appropriately // by bypassing custom constraint message additions return ""; } } if (!markup) { message.append(getPrefixedSplitName(constraint.getContext())).append(" "); } if (displayBody == null || !containsSeverityWord(displayBody)) { String keyword = getValidationKeyword(constraint); if (keyword == null) { keyword = "SHALL"; } message.append(markup ? "<b>" : ""); message.append(keyword); message.append(markup ? "</b>" : ""); message.append(" satisfy: "); } if (displayBody == null) { message.append(constraint.getName()); } else { message.append(displayBody); } appendConformanceRuleIds(constraint, message, markup); if (!markup) { // remove line feeds int index; while ((index = message.indexOf("\r")) >= 0) { message.deleteCharAt(index); } while ((index = message.indexOf("\n")) >= 0) { message.deleteCharAt(index); if (message.charAt(index) != ' ') { message.insert(index, " "); } } } return message.toString(); } private static String computeLogicalConformanceMessage(Constraint constraint, LogicalConstraint logicConstraint, boolean markup) { StringBuffer message = new StringBuffer(); logicConstraint.getMessage(); String keyword = getValidationKeyword(constraint); if (keyword == null) { keyword = "SHALL"; } // Wording for IFTHEN - IF xxx then SHALL yyy if (!logicConstraint.getOperation().equals(LogicalOperator.IFTHEN)) { message.append(markup ? "<b>" : ""); message.append(keyword); message.append(markup ? "</b>" : ""); } switch (logicConstraint.getOperation()) { case XOR: message.append(" contain one and only one of the following "); break; case AND: message.append(" contain all of the following "); break; case OR: message.append(" contain one or more of the following "); case IFTHEN: message.append("if "); break; case NOTBOTH: message.append(" contain zero or one of the following but not both "); break; default: message.append(" satisfy the following "); break; } if (logicConstraint.getOperation().equals(LogicalOperator.IFTHEN) && constraint.getConstrainedElements().size() == 2) { String propertyKeyword = getValidationKeyword(constraint.getConstrainedElements().get(0)); if (propertyKeyword != null) { message.append( computeConformanceMessage(constraint.getConstrainedElements().get(0), markup).replace( propertyKeyword, "")); } else { message.append(computeConformanceMessage(constraint.getConstrainedElements().get(0), markup)); } message.append(" then it ").append(markup ? "<lines>" : "").append( markup ? "<b>" : "").append(keyword).append( markup ? "</b> " : " "); message.append(computeConformanceMessage(constraint.getConstrainedElements().get(1), markup)); message.append(markup ? "</lines>" : ""); } else { if (markup) { message.append("<ul>"); } for (Element element : constraint.getConstrainedElements()) { message.append(LI[0]); message.append(computeConformanceMessage(element, markup)); message.append(LI[1]); } if (markup) { message.append("</ul>"); } } appendConformanceRuleIds(constraint, message, markup); return message.toString(); } private static boolean containsSeverityWord(String text) { return text.indexOf("SHALL") >= 0 || text.indexOf("SHOULD") >= 0 || text.indexOf("MAY") >= 0; } private static String replaceSeverityWithBold(String input) { String output; output = input.replaceAll("SHALL", "<b>SHALL</b>"); output = output.replaceAll("SHOULD", "<b>SHOULD</b>"); output = output.replaceAll("MAY", "<b>MAY</b>"); output = output.replaceAll("\\<b>SHALL\\</b> NOT", "<b>SHALL NOT</b>"); output = output.replaceAll("\\<b>SHOULD\\</b> NOT", "<b>SHOULD NOT</b>"); return output; } /** * FindResourcesByNameVisitor searches the resource for resources of a particular name * You would think there was a method for this already but i could not find it * * @author seanmuir * */ public static class FindResourcesByNameVisitor implements IResourceVisitor { private String resourceName; private ArrayList<IResource> resources = new ArrayList<IResource>(); /** * @return the resources */ public ArrayList<IResource> getResources() { return resources; } /** * @param resourceName */ public FindResourcesByNameVisitor(String resourceName) { super(); this.resourceName = resourceName; } /* * (non-Javadoc) * * @see org.eclipse.core.resources.IResourceVisitor#visit(org.eclipse.core.resources.IResource) */ public boolean visit(IResource arg0) throws CoreException { if (resourceName != null && resourceName.equals(arg0.getName())) { resources.add(arg0); } return true; } } public static IProject getElementModelProject(Element element) { try { Package elementPackage = UMLUtil.getTopPackage(element); if (elementPackage != null && elementPackage.eResource() != null) { FindResourcesByNameVisitor visitor = new FindResourcesByNameVisitor( elementPackage.eResource().getURI().lastSegment()); IWorkspace iw = org.eclipse.core.resources.ResourcesPlugin.getWorkspace(); iw.getRoot().accept(visitor); if (!visitor.getResources().isEmpty()) { return visitor.getResources().get(0).getProject(); } } } catch (CoreException e) { // If there is an issue with the workspace - return null } return null; } public static IProject getModelDocProject(IProject modelProject) { if (modelProject != null && modelProject.exists()) { return org.eclipse.core.resources.ResourcesPlugin.getWorkspace().getRoot().getProject( modelProject.getName().replace(".model", ".doc")); } return null; } /** * computeXref returns the XREF for DITA publication * * TODO Refactor and move out of model util * * @param source * @param target * @return */ public static String computeXref(Element source, Classifier target) { if (target == null) { return null; } if (target instanceof Enumeration) { return computeTerminologyXref(source, (Enumeration) target); } if (UMLUtil.isSameProject(source, target)) { return "../" + normalizeCodeName(target.getName()) + ".dita"; } // If the model project is available (should be) and the dita content is part of the doc project if (!isCDAModel(target)) { IProject sourceProject = getElementModelProject(source); sourceProject = getModelDocProject(sourceProject); IProject targetProject = getElementModelProject(target); targetProject = getModelDocProject(targetProject); if (targetProject != null && sourceProject != null) { IPath projectPath = new Path("/dita/classes/" + targetProject.getName()); IFolder referenceDitaFolder = sourceProject.getFolder(projectPath); if (referenceDitaFolder.exists()) { return "../" + targetProject.getName() + "/classes/" + normalizeCodeName(target.getName()) + ".dita"; } } String pathFolder = "classes"; String basePackage = ""; String prefix = ""; String packageName = target.getNearestPackage().getName(); if (RIMModelUtil.RIM_PACKAGE_NAME.equals(packageName)) { basePackage = "org.openhealthtools.mdht.uml.hl7.rim"; } else if (CDA_PACKAGE_NAME.equals(packageName)) { basePackage = "org.openhealthtools.mdht.uml.cda"; } else { basePackage = getModelBasePackage(target); prefix = getModelNamespacePrefix(target); } if (basePackage == null || basePackage.trim().length() == 0) { basePackage = "org.openhealthtools.mdht.uml.cda"; } if (prefix != null && prefix.trim().length() > 0) { prefix += "."; } return INFOCENTER_URL + "/topic/" + basePackage + "." + prefix + "doc/" + pathFolder + "/" + normalizeCodeName(target.getName()) + ".html"; } return null; } protected static String computeTerminologyXref(Element source, Enumeration target) { String href = null; if (UMLUtil.isSameProject(source, target)) { href = "../../terminology/" + normalizeCodeName(target.getName()) + ".dita"; } return href; } public static Property getNavigableEnd(Association association) { Property navigableEnd = null; for (Property end : association.getMemberEnds()) { if (end.isNavigable()) { if (navigableEnd != null) { return null; // multiple navigable ends } navigableEnd = end; } } return navigableEnd; } /** * getExtensionNamespace returns the name space from a extension package in the CDA model * * @param type * @return */ private static String getExtensionNamespace(Type type) { String nameSpace = null; if (type != null && type.getNearestPackage() != null && !CDA_PACKAGE_NAME.equals(type.getNearestPackage().getName())) { Stereotype ecoreStereotype = type.getNearestPackage().getAppliedStereotype(EPACKAGE); if (ecoreStereotype != null) { Object object = type.getNearestPackage().getValue(ecoreStereotype, NSPREFIX); if (object instanceof String) { nameSpace = (String) object; } } } return nameSpace; } public static String getNameSpacePrefix(Class cdaSourceClass) { if (cdaSourceClass != null && cdaSourceClass.getPackage() != null && !CDA_PACKAGE_NAME.equals(cdaSourceClass.getPackage().getName())) { Stereotype ecoreStereotype = cdaSourceClass.getPackage().getAppliedStereotype(EPACKAGE); if (ecoreStereotype != null) { Object object = cdaSourceClass.getPackage().getValue(ecoreStereotype, NSPREFIX); if (object instanceof String) { return (String) object; } } } return null; } /** * getCDAElementName - Returns the CDA Element name as a string * * @TODO Refactor to use org.openhealthtools.mdht.uml.transform.ecore.TransformAbstract.getInitialProperty(Property) * * Currently walk the redefines to see if we can match the CDA property using the name and type * If none found - for backwards compatibility we look for a property in the base class with a matching type which is potential error prone * If none still - leverage the getassociation * * @param property * @return */ public static String getCDAElementName(Property property) { String elementName = null; if (property.getType() instanceof Class) { Class cdaSourceClass = getCDAClass(property.getClass_()); if (cdaSourceClass != null) { // First check for definitions for (Property redefinedProperty : property.getRedefinedProperties()) { // This will never succeed for associations, does not include ActRelationship if (redefinedProperty.getType() != null) { Property cdaProperty = cdaSourceClass.getOwnedAttribute( redefinedProperty.getName(), getCDAClass((Classifier) redefinedProperty.getType())); if (cdaProperty != null && cdaProperty.getName() != null) { String modelPrefix = getExtensionNamespace(cdaProperty.getType()); elementName = !StringUtils.isEmpty(modelPrefix) ? modelPrefix + ":" + cdaProperty.getName() : cdaProperty.getName(); break; } } } // Next check using property type and name if (elementName == null) { Property cdaProperty = cdaSourceClass.getOwnedAttribute( property.getName(), getCDAClass((Classifier) property.getType())); if (cdaProperty != null && cdaProperty.getName() != null) { String modelPrefix = getExtensionNamespace(cdaProperty.getType()); elementName = !StringUtils.isEmpty(modelPrefix) ? modelPrefix + ":" + cdaProperty.getName() : cdaProperty.getName(); } } // Ultimately use original logic for backwards compatibility if (elementName == null) { Property cdaProperty = cdaSourceClass.getOwnedAttribute( null, getCDAClass((Classifier) property.getType())); if (cdaProperty != null && cdaProperty.getName() != null) { String modelPrefix = getExtensionNamespace(cdaProperty.getType()); elementName = !StringUtils.isEmpty(modelPrefix) ? modelPrefix + ":" + cdaProperty.getName() : cdaProperty.getName(); } } } } // look for CDA association class element name, e.g. "component" if (elementName == null) { elementName = getCDAAssociationElementName(property); } if (elementName == null) { elementName = property.getName(); } return elementName; } public static String getCDAAssociationElementName(Property property) { Class cdaSourceClass = getCDAClass(property.getClass_()); Class endType = (property.getType() instanceof Class) ? (Class) property.getType() : null; Class cdaTargetClass = endType != null ? getCDAClass(endType) : null; // This is incomplete determination of XML element name, but same logic as used in model transform String elementName = null; if (cdaSourceClass == null) { elementName = property.getName(); } else if ("ClinicalDocument".equals(cdaSourceClass.getName()) && (CDAModelUtil.isSection(cdaTargetClass) || CDAModelUtil.isClinicalStatement(cdaTargetClass))) { elementName = "component"; } else if (CDAModelUtil.isSection(cdaSourceClass) && (CDAModelUtil.isSection(cdaTargetClass))) { elementName = "component"; } else if (CDAModelUtil.isSection(cdaSourceClass) && (CDAModelUtil.isClinicalStatement(cdaTargetClass) || CDAModelUtil.isEntry(cdaTargetClass))) { elementName = "entry"; } else if (CDAModelUtil.isOrganizer(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) { elementName = "component"; } else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) { elementName = "entryRelationship"; } else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && cdaTargetClass != null && "ParticipantRole".equals(cdaTargetClass.getName())) { elementName = "participant"; } else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && cdaTargetClass != null && "AssignedEntity".equals(cdaTargetClass.getName())) { elementName = "performer"; } return elementName; } private static String getMultiplicityRange(Property property) { StringBuffer message = new StringBuffer(); String lower = Integer.toString(property.getLower()); String upper = property.getUpper() == -1 ? "*" : Integer.toString(property.getUpper()); message.append(" [").append(lower).append("..").append(upper).append("]"); return message.toString(); } private static String getMultiplicityText(Property property) { StringBuffer message = new StringBuffer(); if (property.getLower() == property.getUpper()) { // Upper and lower equal and not zero if (property.getLower() != 0) { message.append("exactly ").append(convertNumberToWords(property.getUpper())); } } else if (property.getLower() == 0) { // Lower is zero if (property.getUpper() == 0) { } else if (property.getUpper() == 1) { message.append("zero or one"); } else if (property.getUpper() == -1) { message.append("zero or more"); } else { message.append("not more than " + convertNumberToWords(property.getUpper())); } } else if (property.getLower() == 1) { // Lower is one if (property.getUpper() == -1) { message.append("at least one"); } else { message.append( "at least " + convertNumberToWords(property.getLower()) + " and not more than " + convertNumberToWords(property.getUpper())); } } else { // Lower is greater then 1 message.append("at least " + convertNumberToWords(property.getLower())); if (property.getUpper() != -1) { message.append(" and not more than " + convertNumberToWords(property.getUpper())); } } return message.toString(); } // This snippet may be used freely, as long as the authorship note remains in the source code. private static final String[] lowNames = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tensNames = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; private static final String[] bigNames = { "thousand", "million", "billion" }; private static String convertNumberToWords(int n) { if (n < 0) { return "minus " + convertNumberToWords(-n); } if (n <= 999) { return convert999(n); } String s = null; int t = 0; while (n > 0) { if (n % 1000 != 0) { String s2 = convert999(n % 1000); if (t > 0) { s2 = s2 + " " + bigNames[t - 1]; } if (s == null) { s = s2; } else { s = s2 + ", " + s; } } n /= 1000; t++; } return s; } // Range 0 to 999. private static String convert999(int n) { String s1 = lowNames[n / 100] + " hundred"; String s2 = convert99(n % 100); if (n <= 99) { return s2; } else if (n % 100 == 0) { return s1; } else { return s1 + " " + s2; } } // Range 0 to 99. private static String convert99(int n) { if (n < 20) { return lowNames[n]; } String s = tensNames[n / 10 - 2]; if (n % 10 == 0) { return s; } return s + "-" + lowNames[n % 10]; } public static boolean isXMLAttribute(Property property) { Property cdaProperty = getCDAProperty(property); if (cdaProperty != null) { Stereotype eAttribute = cdaProperty.getAppliedStereotype("Ecore::EAttribute"); if (eAttribute != null) { return true; } } return false; } private static String getMultiplicityRange(Class template) { String templateId = null; Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE); if (hl7Template != null && template.hasValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_MULTIPLICITY)) { templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_MULTIPLICITY); } else { for (Classifier parent : template.getGenerals()) { templateId = getMultiplicityRange((Class) parent); if (templateId != null) { break; } } } return templateId; } public static String getTemplateId(Class template) { String templateId = null; Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE); if (hl7Template != null) { templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_TEMPLATE_ID); } else { for (Classifier parent : template.getGenerals()) { templateId = getTemplateId((Class) parent); if (templateId != null) { break; } } } return templateId; } public static String getTemplateVersion(Class template) { String templateVersion = null; Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE); if (hl7Template != null) { templateVersion = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_VERSION); } else { for (Classifier parent : template.getGenerals()) { templateVersion = getTemplateId((Class) parent); if (templateVersion != null) { break; } } } return templateVersion; } public static String getModelPrefix(Element element) { String prefix = null; Package thePackage = UMLUtil.getTopPackage(element); if (thePackage != null) { Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype( thePackage, ICDAProfileConstants.CODEGEN_SUPPORT); if (codegenSupport != null) { prefix = (String) thePackage.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_PREFIX); } else if (CDA_PACKAGE_NAME.equals(thePackage.getName())) { prefix = "CDA"; } else if (RIMModelUtil.RIM_PACKAGE_NAME.equals(thePackage.getName())) { prefix = "RIM"; } } return prefix != null ? prefix : ""; } public static String getModelNamespacePrefix(Element element) { String prefix = null; Package model = UMLUtil.getTopPackage(element); Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT); if (codegenSupport != null) { prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_PREFIX); } return prefix; } public static String getModelBasePackage(Element element) { String basePackage = null; Package model = UMLUtil.getTopPackage(element); Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT); if (codegenSupport != null) { basePackage = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_BASE_PACKAGE); } return basePackage; } public static String getEcorePackageURI(Element element) { String nsURI = null; Package model = UMLUtil.getTopPackage(element); Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT); if (codegenSupport != null) { nsURI = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_URI); } if (nsURI == null) { // for base models without codegenSupport if (model.getName().equals("cda")) { nsURI = "urn:hl7-org:v3"; } else if (model.getName().equals("datatypes")) { nsURI = "http: } else if (model.getName().equals("vocab")) { nsURI = "http: } } return nsURI; } public static String getPrefixedSplitName(NamedElement element) { StringBuffer buffer = new StringBuffer(); String modelPrefix = getModelPrefix(element); if (modelPrefix != null && modelPrefix.length() > 0) { buffer.append(modelPrefix).append(" "); } buffer.append(UMLUtil.splitName(element)); return buffer.toString(); } /** * Returns a list conformance rule IDs. */ public static List<String> getConformanceRuleIdList(Element element) { List<String> ruleIds = new ArrayList<String>(); Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION); if (validationSupport != null) { Validation validation = (Validation) element.getStereotypeApplication(validationSupport); for (String ruleId : validation.getRuleId()) { ruleIds.add(ruleId); } } return ruleIds; } protected static void appendTerminologyConformanceRuleIds(Property property, StringBuffer message, boolean markup) { String ruleIds = getTerminologyConformanceRuleIds(property); if (ruleIds.length() > 0) { message.append(" ("); message.append(ruleIds); message.append(")"); } } protected static void appendConformanceRuleIds(Property property, StringBuffer message, boolean markup) { String ruleIds = getConformanceRuleIds(property); if (ruleIds.length() > 0) { message.append(" ("); message.append(ruleIds); message.append(")"); } } protected static void appendConformanceRuleIds(Association association, StringBuffer message, boolean markup) { String ruleIds = getConformanceRuleIds(association); if (ruleIds.length() > 0) { message.append(" ("); message.append(ruleIds); message.append(")"); } } protected static void appendConformanceRuleIds(Element element, StringBuffer message, boolean markup) { String ruleIds = getConformanceRuleIds(element); if (ruleIds.length() > 0) { message.append(" ("); message.append(ruleIds); message.append(")"); } } protected static void appendConformanceRuleIds(Element element, Stereotype stereotype, StringBuffer message, boolean markup) { String ruleIds = getConformanceRuleIds(element, stereotype); if (ruleIds.length() > 0) { message.append(" ("); message.append(ruleIds); message.append(")"); } } /** * Returns a comma separated list of conformance rule IDs, or an empty string if no IDs. */ public static String getConformanceRuleIds(Property property) { Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype( property, ICDAProfileConstants.PROPERTY_VALIDATION); return getConformanceRuleIds(property, validationSupport); } /** * Returns a comma separated list of conformance rule IDs, or an empty string if no IDs. */ public static String getTerminologyConformanceRuleIds(Property property) { Stereotype terminologyConstraint = getTerminologyConstraint(property); return getConformanceRuleIds(property, terminologyConstraint); } /** * Returns a comma separated list of conformance rule IDs, or an empty string if no IDs. */ public static String getConformanceRuleIds(Association association) { Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype( association, ICDAProfileConstants.ASSOCIATION_VALIDATION); return getConformanceRuleIds(association, validationSupport); } /** * Returns a comma separated list of conformance rule IDs, or an empty string if no IDs. */ public static String getConformanceRuleIds(Element element) { Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION); return getConformanceRuleIds(element, validationSupport); } public static String getConformanceRuleIds(Element element, Stereotype validationSupport) { StringBuffer ruleIdDisplay = new StringBuffer(); if (validationSupport != null) { Validation validation = (Validation) element.getStereotypeApplication(validationSupport); for (String ruleId : validation.getRuleId()) { if (ruleIdDisplay.length() > 0) { ruleIdDisplay.append(", "); } ruleIdDisplay.append(ruleId); } } return ruleIdDisplay.toString(); } public static Stereotype getTerminologyConstraint(Element element) { Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype( element, ITermProfileConstants.CONCEPT_DOMAIN_CONSTRAINT); if (stereotype == null) { stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT); } if (stereotype == null) { stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ITermProfileConstants.VALUE_SET_CONSTRAINT); } return stereotype; } public static boolean hasValidationSupport(Element element) { Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION); return validationSupport != null; } /** * @deprecated Use {@link #getValidationSeverity(Property, String)} to get the severity for a specific validation stereotype. * If necessary, this can be the abstract {@link ICDAProfileConstants#VALIDATION Validation} stereotype to get any available * validation severity. */ @Deprecated public static String getValidationSeverity(Property property) { return getValidationSeverity(property, ICDAProfileConstants.PROPERTY_VALIDATION); } public static String getValidationSeverity(Property property, String validationStereotypeName) { Stereotype validationStereotype = CDAProfileUtil.getAppliedCDAStereotype(property, validationStereotypeName); return getValidationSeverity(property, validationStereotype); } public static String getValidationSeverity(Element element) { // use first available validation stereotype return getValidationSeverity(element, ICDAProfileConstants.VALIDATION); } public static String getValidationSeverity(Element element, String validationStereotypeName) { Stereotype validationStereotype = CDAProfileUtil.getAppliedCDAStereotype(element, validationStereotypeName); return getValidationSeverity(element, validationStereotype); } public static String getValidationSeverity(Element element, Stereotype validationStereotype) { String severity = null; if ((validationStereotype != null) && CDAProfileUtil.isValidationStereotype(validationStereotype)) { Object value = element.getValue(validationStereotype, ICDAProfileConstants.VALIDATION_SEVERITY); if (value instanceof EnumerationLiteral) { severity = ((EnumerationLiteral) value).getName(); } else if (value instanceof Enumerator) { severity = ((Enumerator) value).getName(); } } return severity; } public static String getValidationKeywordWithPropertyRange(Property property) { String keyword = getValidationKeyword(property); return addShallNot(keyword, property); } public static String getValidationKeyword(Property property) { String severity = getValidationSeverity(property, ICDAProfileConstants.PROPERTY_VALIDATION); if (severity == null) { // get other validation stereotype, usually for terminology severity = getValidationSeverity((Element) property); } return getValidationKeyword(severity); } public static String getValidationKeywordWithPropertyRange(Element element, Property property) { // use first available validation stereotype String keyword = getValidationKeyword(element); return addShallNot(keyword, property); } private static String addShallNot(String keyword, Property property) { if (property.getLower() == 0 && property.getUpper() == 0 && ("SHALL".equals(keyword) || "SHOULD".equals(keyword))) { keyword += " NOT"; } return keyword; } public static String getValidationKeyword(Element element) { // use first available validation stereotype String severity = getValidationSeverity(element); return getValidationKeyword(severity); } public static String getValidationKeyword(Element element, Stereotype validationStereotype) { String severity = getValidationSeverity(element, validationStereotype); return getValidationKeyword(severity); } private static String getValidationKeyword(String severity) { String keyword = null; if (SEVERITY_INFO.equals(severity)) { keyword = "MAY"; } else if (SEVERITY_WARNING.equals(severity)) { keyword = "SHOULD"; } else if (SEVERITY_ERROR.equals(severity)) { keyword = "SHALL"; } return keyword; } public static void setValidationMessage(Element constrainedElement, String message) { Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype( constrainedElement, ICDAProfileConstants.VALIDATION); if (validationSupport != null) { constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE, message); } } protected static String getLiteralValue(Element element, Stereotype stereotype, String propertyName) { Object value = element.getValue(stereotype, propertyName); String name = null; if (value instanceof EnumerationLiteral) { name = ((EnumerationLiteral) value).getName(); } else if (value instanceof Enumerator) { name = ((Enumerator) value).getName(); } return name; } protected static String getLiteralValueLabel(Element element, Stereotype stereotype, String propertyName, Enumeration umlEnumeration) { Object value = element.getValue(stereotype, propertyName); String name = null; if (value instanceof EnumerationLiteral) { name = ((EnumerationLiteral) value).getLabel(); } else if (value instanceof Enumerator) { name = ((Enumerator) value).getName(); if (umlEnumeration != null) { name = umlEnumeration.getOwnedLiteral(name).getLabel(); } } return name; } public static String fixNonXMLCharacters(String text) { if (text == null) { return null; } StringBuffer newText = new StringBuffer(); for (int i = 0; i < text.length(); i++) { // test for unicode characters from copy/paste of MS Word text if (text.charAt(i) == '\u201D') { newText.append("\""); } else if (text.charAt(i) == '\u201C') { newText.append("\""); } else if (text.charAt(i) == '\u2019') { newText.append("'"); } else if (text.charAt(i) == '\u2018') { newText.append("'"); } else { newText.append(text.charAt(i)); } } return newText.toString(); } public static String escapeMarkupCharacters(String text) { if (text == null) { return null; } text = fixNonXMLCharacters(text); StringBuffer newText = new StringBuffer(); for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '<') { newText.append("&lt;"); } else if (text.charAt(i) == '>') { newText.append("&gt;"); } else { newText.append(text.charAt(i)); } } return newText.toString(); } public static String normalizeCodeName(String name) { String result = ""; String[] parts = name.split(" "); for (String part : parts) { result += part.substring(0, 1).toUpperCase() + part.substring(1); } result = UML2Util.getValidJavaIdentifier(result); return result; } private static String mandatoryOrNotMessage(Property curProperty) { // capture if allows nullFlavor or not boolean mandatory = CDAProfileUtil.isMandatory(curProperty); // mandatory implies nullFlavor is NOT allowed ", where the @code " // non-mandatory implies nullFlavor is allowed ", which " // return the proper message based on mandatory or not return mandatory ? ", where the @code " : ", which "; } public static boolean isInlineClass(Class _class) { Inline inline = CDAProfileUtil.getInline(_class); if (inline != null) { return true; } if (_class.getOwner() instanceof Class) { return true; } for (Comment comment : _class.getOwnedComments()) { if (comment.getBody().startsWith("INLINE")) { return true; } } return false; } public static String getInlineFilter(Class inlineClass) { Inline inline = CDAProfileUtil.getInline(inlineClass); if (inline != null) { return inline.getFilter() != null ? inline.getFilter() : ""; } String filter = ""; for (Comment comment : inlineClass.getOwnedComments()) { if (comment.getBody().startsWith("INLINE&")) { String[] temp = comment.getBody().split("&"); if (temp.length == 2) { filter = String.format("->select(%s)", temp[1]); } break; } } if ("".equals(filter)) { // search hierarchy for (Classifier next : inlineClass.getGenerals()) { if (next instanceof Class) { filter = getInlineFilter((Class) next); if (!"".equals(filter)) { break; } } } } return filter; } public static boolean isPublishSeperately(Class _class) { boolean publish = false; Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(_class, ICDAProfileConstants.INLINE); if (stereotype != null) { Boolean result = (Boolean) _class.getValue(stereotype, "publishSeperately"); publish = result.booleanValue(); } return publish; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1261"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.raoulvdberge.refinedstorage.apiimpl.network.node; import com.raoulvdberge.refinedstorage.RS; import com.raoulvdberge.refinedstorage.RSBlocks; import com.raoulvdberge.refinedstorage.RSItems; import com.raoulvdberge.refinedstorage.api.network.INetwork; import com.raoulvdberge.refinedstorage.api.network.grid.GridType; import com.raoulvdberge.refinedstorage.api.network.grid.IGrid; import com.raoulvdberge.refinedstorage.api.network.grid.IGridNetworkAware; import com.raoulvdberge.refinedstorage.api.network.grid.IGridTab; import com.raoulvdberge.refinedstorage.api.network.grid.handler.IFluidGridHandler; import com.raoulvdberge.refinedstorage.api.network.grid.handler.IItemGridHandler; import com.raoulvdberge.refinedstorage.api.network.item.INetworkItem; import com.raoulvdberge.refinedstorage.api.network.item.NetworkItemAction; import com.raoulvdberge.refinedstorage.api.network.security.Permission; import com.raoulvdberge.refinedstorage.api.storage.IStorageCache; import com.raoulvdberge.refinedstorage.api.storage.IStorageCacheListener; import com.raoulvdberge.refinedstorage.api.util.IComparer; import com.raoulvdberge.refinedstorage.api.util.IFilter; import com.raoulvdberge.refinedstorage.apiimpl.API; import com.raoulvdberge.refinedstorage.apiimpl.storage.StorageCacheListenerGridFluid; import com.raoulvdberge.refinedstorage.apiimpl.storage.StorageCacheListenerGridItem; import com.raoulvdberge.refinedstorage.block.BlockGrid; import com.raoulvdberge.refinedstorage.inventory.ItemHandlerBase; import com.raoulvdberge.refinedstorage.inventory.ItemHandlerFilter; import com.raoulvdberge.refinedstorage.inventory.ItemHandlerListenerNetworkNode; import com.raoulvdberge.refinedstorage.inventory.ItemValidatorBasic; import com.raoulvdberge.refinedstorage.item.ItemPattern; import com.raoulvdberge.refinedstorage.tile.data.TileDataManager; import com.raoulvdberge.refinedstorage.tile.grid.TileGrid; import com.raoulvdberge.refinedstorage.util.StackUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.*; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.items.wrapper.CombinedInvWrapper; import net.minecraftforge.items.wrapper.InvWrapper; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; public class NetworkNodeGrid extends NetworkNode implements IGridNetworkAware { public static final String ID = "grid"; public static final String NBT_VIEW_TYPE = "ViewType"; public static final String NBT_SORTING_DIRECTION = "SortingDirection"; public static final String NBT_SORTING_TYPE = "SortingType"; public static final String NBT_SEARCH_BOX_MODE = "SearchBoxMode"; public static final String NBT_OREDICT_PATTERN = "OredictPattern"; public static final String NBT_TAB_SELECTED = "TabSelected"; public static final String NBT_TAB_PAGE = "TabPage"; public static final String NBT_SIZE = "Size"; public static final String NBT_PROCESSING_PATTERN = "ProcessingPattern"; private Container craftingContainer = new Container() { @Override public boolean canInteractWith(EntityPlayer player) { return false; } @Override public void onCraftMatrixChanged(IInventory inventory) { onCraftingMatrixChanged(); } }; private IRecipe currentRecipe; private InventoryCrafting matrix = new InventoryCrafting(craftingContainer, 3, 3); private InventoryCraftResult result = new InventoryCraftResult(); private ItemHandlerBase matrixProcessing = new ItemHandlerBase(9 * 2, new ItemHandlerListenerNetworkNode(this)); private ItemHandlerBase patterns = new ItemHandlerBase(2, new ItemHandlerListenerNetworkNode(this), new ItemValidatorBasic(RSItems.PATTERN)) { @Override protected void onContentsChanged(int slot) { super.onContentsChanged(slot); ItemStack pattern = getStackInSlot(slot); if (slot == 1 && !pattern.isEmpty()) { boolean isPatternProcessing = ItemPattern.isProcessing(pattern); if (isPatternProcessing && isProcessingPattern()) { for (int i = 0; i < 9; ++i) { matrixProcessing.setStackInSlot(i, StackUtils.nullToEmpty(ItemPattern.getInputSlot(pattern, i))); } for (int i = 0; i < 9; ++i) { matrixProcessing.setStackInSlot(9 + i, StackUtils.nullToEmpty(ItemPattern.getOutputSlot(pattern, i))); } } else if (!isPatternProcessing && !isProcessingPattern()) { for (int i = 0; i < 9; ++i) { matrix.setInventorySlotContents(i, StackUtils.nullToEmpty(ItemPattern.getInputSlot(pattern, i))); } } } } @Override public int getSlotLimit(int slot) { return slot == 1 ? 1 : super.getSlotLimit(slot); } @Nonnull @Override public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { // Allow in slot 0 // Disallow in slot 1 // Only allow in slot 1 when it isn't a blank pattern // This makes it so that written patterns can be re-inserted in slot 1 to be overwritten again // This makes it so that blank patterns can't be inserted in slot 1 through hoppers. if (slot == 0 || stack.getTagCompound() != null) { return super.insertItem(slot, stack, simulate); } return stack; } }; private List<IFilter> filters = new ArrayList<>(); private List<IGridTab> tabs = new ArrayList<>(); private ItemHandlerFilter filter = new ItemHandlerFilter(filters, tabs, new ItemHandlerListenerNetworkNode(this)); private GridType type; private int viewType = VIEW_TYPE_NORMAL; private int sortingDirection = SORTING_DIRECTION_DESCENDING; private int sortingType = SORTING_TYPE_QUANTITY; private int searchBoxMode = SEARCH_BOX_MODE_NORMAL; private int size = SIZE_STRETCH; private int tabSelected = -1; private int tabPage = 0; private boolean oredictPattern = false; private boolean processingPattern = false; public NetworkNodeGrid(World world, BlockPos pos) { super(world, pos); } @Override public int getEnergyUsage() { switch (getType()) { case NORMAL: return RS.INSTANCE.config.gridUsage; case CRAFTING: return RS.INSTANCE.config.craftingGridUsage; case PATTERN: return RS.INSTANCE.config.patternGridUsage; case FLUID: return RS.INSTANCE.config.fluidGridUsage; default: return 0; } } public void setViewType(int viewType) { this.viewType = viewType; } public void setSortingDirection(int sortingDirection) { this.sortingDirection = sortingDirection; } public void setSortingType(int sortingType) { this.sortingType = sortingType; } public void setSearchBoxMode(int searchBoxMode) { this.searchBoxMode = searchBoxMode; } public void setTabSelected(int tabSelected) { this.tabSelected = tabSelected; } public void setTabPage(int page) { this.tabPage = page; } public void setSize(int size) { this.size = size; } public boolean isOredictPattern() { return oredictPattern; } public void setOredictPattern(boolean oredictPattern) { this.oredictPattern = oredictPattern; } public boolean isProcessingPattern() { return world.isRemote ? TileGrid.PROCESSING_PATTERN.getValue() : processingPattern; } public void setProcessingPattern(boolean processingPattern) { this.processingPattern = processingPattern; } public GridType getType() { if (type == null && world.getBlockState(pos).getBlock() == RSBlocks.GRID) { type = (GridType) world.getBlockState(pos).getValue(BlockGrid.TYPE); } return type == null ? GridType.NORMAL : type; } @Override public IStorageCacheListener createListener(EntityPlayerMP player) { return getType() == GridType.FLUID ? new StorageCacheListenerGridFluid(player, network) : new StorageCacheListenerGridItem(player, network); } @Nullable @Override public IStorageCache getStorageCache() { return network != null ? (getType() == GridType.FLUID ? network.getFluidStorageCache() : network.getItemStorageCache()) : null; } @Nullable @Override public IItemGridHandler getItemHandler() { return network != null ? network.getItemGridHandler() : null; } @Nullable @Override public IFluidGridHandler getFluidHandler() { return network != null ? network.getFluidGridHandler() : null; } @Override public String getGuiTitle() { GridType type = getType(); switch (type) { case CRAFTING: return "gui.refinedstorage:crafting_grid"; case PATTERN: return "gui.refinedstorage:pattern_grid"; case FLUID: return "gui.refinedstorage:fluid_grid"; default: return "gui.refinedstorage:grid"; } } public IItemHandler getPatterns() { return patterns; } @Override public IItemHandlerModifiable getFilter() { return filter; } @Override public List<IFilter> getFilters() { return filters; } @Override public List<IGridTab> getTabs() { return tabs; } @Override public InventoryCrafting getCraftingMatrix() { return matrix; } @Override public InventoryCraftResult getCraftingResult() { return result; } public ItemHandlerBase getProcessingMatrix() { return matrixProcessing; } @Override public void onCraftingMatrixChanged() { if (currentRecipe == null || !currentRecipe.matches(matrix, world)) { currentRecipe = CraftingManager.findMatchingRecipe(matrix, world); } if (currentRecipe == null) { result.setInventorySlotContents(0, ItemStack.EMPTY); } else { result.setInventorySlotContents(0, currentRecipe.getCraftingResult(matrix)); } markDirty(); } @Override public void onRecipeTransfer(EntityPlayer player, ItemStack[][] recipe) { onRecipeTransfer(this, player, recipe); } public static void onRecipeTransfer(IGridNetworkAware grid, EntityPlayer player, ItemStack[][] recipe) { INetwork network = grid.getNetwork(); if (network != null && grid.getType() == GridType.CRAFTING && !network.getSecurityManager().hasPermission(Permission.EXTRACT, player)) { return; } // First try to empty the crafting matrix for (int i = 0; i < grid.getCraftingMatrix().getSizeInventory(); ++i) { ItemStack slot = grid.getCraftingMatrix().getStackInSlot(i); if (!slot.isEmpty()) { // Only if we are a crafting grid. Pattern grids can just be emptied. if (grid.getType() == GridType.CRAFTING) { // If we are connected, try to insert into network. If it fails, stop. if (network != null) { if (network.insertItem(slot, slot.getCount(), true) != null) { return; } else { network.insertItem(slot, slot.getCount(), false); } } else { // If we aren't connected, try to insert into player inventory. If it fails, stop. if (!player.inventory.addItemStackToInventory(slot.copy())) { return; } } } grid.getCraftingMatrix().setInventorySlotContents(i, ItemStack.EMPTY); } } // Now let's fill the matrix for (int i = 0; i < grid.getCraftingMatrix().getSizeInventory(); ++i) { if (recipe[i] != null) { ItemStack[] possibilities = recipe[i]; // If we are a crafting grid if (grid.getType() == GridType.CRAFTING) { boolean found = false; // If we are connected, first try to get the possibilities from the network if (network != null) { for (ItemStack possibility : possibilities) { ItemStack took = network.extractItem(possibility, 1, IComparer.COMPARE_NBT | (possibility.getItem().isDamageable() ? 0 : IComparer.COMPARE_DAMAGE), false); if (took != null) { grid.getCraftingMatrix().setInventorySlotContents(i, StackUtils.nullToEmpty(took)); found = true; break; } } } // If we haven't found anything in the network (or we are disconnected), go look in the player inventory if (!found) { for (ItemStack possibility : possibilities) { for (int j = 0; j < player.inventory.getSizeInventory(); ++j) { if (API.instance().getComparer().isEqual(possibility, player.inventory.getStackInSlot(j), IComparer.COMPARE_NBT | (possibility.getItem().isDamageable() ? 0 : IComparer.COMPARE_DAMAGE))) { grid.getCraftingMatrix().setInventorySlotContents(i, ItemHandlerHelper.copyStackWithSize(player.inventory.getStackInSlot(j), 1)); player.inventory.decrStackSize(j, 1); found = true; break; } } if (found) { break; } } } } else if (grid.getType() == GridType.PATTERN) { // If we are a pattern grid we can just set the slot grid.getCraftingMatrix().setInventorySlotContents(i, possibilities.length == 0 ? ItemStack.EMPTY : possibilities[0]); } } } } public void clearMatrix() { for (int i = 0; i < matrixProcessing.getSlots(); ++i) { matrixProcessing.setStackInSlot(i, ItemStack.EMPTY); } for (int i = 0; i < matrix.getSizeInventory(); ++i) { matrix.setInventorySlotContents(i, ItemStack.EMPTY); } } @Override public void onClosed(EntityPlayer player) { // NO OP } @Override public void onCrafted(EntityPlayer player) { onCrafted(this, world, player); } public static void onCrafted(IGridNetworkAware grid, World world, EntityPlayer player) { NonNullList<ItemStack> remainder = CraftingManager.getRemainingItems(grid.getCraftingMatrix(), world); INetwork network = grid.getNetwork(); InventoryCrafting matrix = grid.getCraftingMatrix(); for (int i = 0; i < grid.getCraftingMatrix().getSizeInventory(); ++i) { ItemStack slot = matrix.getStackInSlot(i); if (i < remainder.size() && !remainder.get(i).isEmpty()) { // If there is no space for the remainder, dump it in the player inventory if (!slot.isEmpty() && slot.getCount() > 1) { if (!player.inventory.addItemStackToInventory(remainder.get(i).copy())) { ItemStack remainderStack = network == null ? remainder.get(i).copy() : network.insertItem(remainder.get(i).copy(), remainder.get(i).getCount(), false); if (remainderStack != null) { InventoryHelper.spawnItemStack(player.getEntityWorld(), player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ(), remainderStack); } } matrix.decrStackSize(i, 1); } else { matrix.setInventorySlotContents(i, remainder.get(i).copy()); } } else if (!slot.isEmpty()) { if (slot.getCount() == 1 && network != null) { matrix.setInventorySlotContents(i, StackUtils.nullToEmpty(network.extractItem(slot, 1, false))); } else { matrix.decrStackSize(i, 1); } } } grid.onCraftingMatrixChanged(); if (network != null) { INetworkItem networkItem = network.getNetworkItemHandler().getItem(player); if (networkItem != null) { networkItem.onAction(NetworkItemAction.ITEM_CRAFTED); } } } @Override public void onCraftedShift(EntityPlayer player) { onCraftedShift(this, player); } public static void onCraftedShift(IGridNetworkAware grid, EntityPlayer player) { List<ItemStack> craftedItemsList = new ArrayList<>(); int craftedItems = 0; ItemStack crafted = grid.getCraftingResult().getStackInSlot(0); while (true) { grid.onCrafted(player); craftedItemsList.add(crafted.copy()); craftedItems += crafted.getCount(); if (!API.instance().getComparer().isEqual(crafted, grid.getCraftingResult().getStackInSlot(0)) || craftedItems + crafted.getCount() > crafted.getMaxStackSize()) { break; } } INetwork network = grid.getNetwork(); for (ItemStack craftedItem : craftedItemsList) { if (!player.inventory.addItemStackToInventory(craftedItem.copy())) { ItemStack remainder = network == null ? craftedItem : network.insertItem(craftedItem, craftedItem.getCount(), false); if (remainder != null) { InventoryHelper.spawnItemStack(player.getEntityWorld(), player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ(), remainder); } } } FMLCommonHandler.instance().firePlayerCraftingEvent(player, ItemHandlerHelper.copyStackWithSize(crafted, craftedItems), grid.getCraftingMatrix()); } public void onCreatePattern() { if (canCreatePattern()) { if (patterns.getStackInSlot(1).isEmpty()) { patterns.extractItem(0, 1, false); } ItemStack pattern = new ItemStack(RSItems.PATTERN); ItemPattern.setOredict(pattern, oredictPattern); ItemPattern.setProcessing(pattern, processingPattern); if (processingPattern) { for (int i = 0; i < 18; ++i) { if (!matrixProcessing.getStackInSlot(i).isEmpty()) { if (i >= 9) { ItemPattern.setOutputSlot(pattern, i - 9, matrixProcessing.getStackInSlot(i)); } else { ItemPattern.setInputSlot(pattern, i, matrixProcessing.getStackInSlot(i)); } } } } else { for (int i = 0; i < 9; ++i) { ItemStack ingredient = matrix.getStackInSlot(i); if (!ingredient.isEmpty()) { ItemPattern.setInputSlot(pattern, i, ingredient); } } } patterns.setStackInSlot(1, pattern); } } private boolean isPatternAvailable() { return !(patterns.getStackInSlot(0).isEmpty() && patterns.getStackInSlot(1).isEmpty()); } public boolean canCreatePattern() { if (!isPatternAvailable()) { return false; } if (isProcessingPattern()) { int inputsFilled = 0; int outputsFilled = 0; for (int i = 0; i < 9; ++i) { if (!matrixProcessing.getStackInSlot(i).isEmpty()) { inputsFilled++; } } for (int i = 9; i < 18; ++i) { if (!matrixProcessing.getStackInSlot(i).isEmpty()) { outputsFilled++; } } return inputsFilled > 0 && outputsFilled > 0; } else { return !result.getStackInSlot(0).isEmpty() && isPatternAvailable(); } } @Override public int getViewType() { return world.isRemote ? TileGrid.VIEW_TYPE.getValue() : viewType; } @Override public int getSortingDirection() { return world.isRemote ? TileGrid.SORTING_DIRECTION.getValue() : sortingDirection; } @Override public int getSortingType() { return world.isRemote ? TileGrid.SORTING_TYPE.getValue() : sortingType; } @Override public int getSearchBoxMode() { return world.isRemote ? TileGrid.SEARCH_BOX_MODE.getValue() : searchBoxMode; } @Override public int getSize() { return world.isRemote ? TileGrid.SIZE.getValue() : size; } @Override public int getTabSelected() { return world.isRemote ? TileGrid.TAB_SELECTED.getValue() : tabSelected; } @Override public int getTabPage() { return world.isRemote ? TileGrid.TAB_PAGE.getValue() : Math.min(tabPage, getTotalTabPages()); } @Override public int getTotalTabPages() { return (int) Math.floor((float) Math.max(0, tabs.size() - 1) / (float) IGrid.TABS_PER_PAGE); } @Override public void onViewTypeChanged(int type) { TileDataManager.setParameter(TileGrid.VIEW_TYPE, type); } @Override public void onSortingTypeChanged(int type) { TileDataManager.setParameter(TileGrid.SORTING_TYPE, type); } @Override public void onSortingDirectionChanged(int direction) { TileDataManager.setParameter(TileGrid.SORTING_DIRECTION, direction); } @Override public void onSearchBoxModeChanged(int searchBoxMode) { TileDataManager.setParameter(TileGrid.SEARCH_BOX_MODE, searchBoxMode); } @Override public void onSizeChanged(int size) { TileDataManager.setParameter(TileGrid.SIZE, size); } @Override public void onTabSelectionChanged(int tab) { TileDataManager.setParameter(TileGrid.TAB_SELECTED, tab); } @Override public void onTabPageChanged(int page) { if (page >= 0 && page <= getTotalTabPages()) { TileDataManager.setParameter(TileGrid.TAB_PAGE, page); } } @Override public boolean hasConnectivityState() { return true; } @Override public void read(NBTTagCompound tag) { super.read(tag); StackUtils.readItems(matrix, 0, tag); StackUtils.readItems(patterns, 1, tag); StackUtils.readItems(filter, 2, tag); StackUtils.readItems(matrixProcessing, 3, tag); if (tag.hasKey(NBT_TAB_SELECTED)) { tabSelected = tag.getInteger(NBT_TAB_SELECTED); } if (tag.hasKey(NBT_TAB_PAGE)) { tabPage = tag.getInteger(NBT_TAB_PAGE); } } @Override public String getId() { return ID; } @Override public NBTTagCompound write(NBTTagCompound tag) { super.write(tag); StackUtils.writeItems(matrix, 0, tag); StackUtils.writeItems(patterns, 1, tag); StackUtils.writeItems(filter, 2, tag); StackUtils.writeItems(matrixProcessing, 3, tag); tag.setInteger(NBT_TAB_SELECTED, tabSelected); tag.setInteger(NBT_TAB_PAGE, tabPage); return tag; } @Override public NBTTagCompound writeConfiguration(NBTTagCompound tag) { super.writeConfiguration(tag); tag.setInteger(NBT_VIEW_TYPE, viewType); tag.setInteger(NBT_SORTING_DIRECTION, sortingDirection); tag.setInteger(NBT_SORTING_TYPE, sortingType); tag.setInteger(NBT_SEARCH_BOX_MODE, searchBoxMode); tag.setInteger(NBT_SIZE, size); tag.setBoolean(NBT_OREDICT_PATTERN, oredictPattern); tag.setBoolean(NBT_PROCESSING_PATTERN, processingPattern); return tag; } @Override public void readConfiguration(NBTTagCompound tag) { super.readConfiguration(tag); if (tag.hasKey(NBT_VIEW_TYPE)) { viewType = tag.getInteger(NBT_VIEW_TYPE); } if (tag.hasKey(NBT_SORTING_DIRECTION)) { sortingDirection = tag.getInteger(NBT_SORTING_DIRECTION); } if (tag.hasKey(NBT_SORTING_TYPE)) { sortingType = tag.getInteger(NBT_SORTING_TYPE); } if (tag.hasKey(NBT_SEARCH_BOX_MODE)) { searchBoxMode = tag.getInteger(NBT_SEARCH_BOX_MODE); } if (tag.hasKey(NBT_SIZE)) { size = tag.getInteger(NBT_SIZE); } if (tag.hasKey(NBT_OREDICT_PATTERN)) { oredictPattern = tag.getBoolean(NBT_OREDICT_PATTERN); } if (tag.hasKey(NBT_PROCESSING_PATTERN)) { processingPattern = tag.getBoolean(NBT_PROCESSING_PATTERN); } } @Override public IItemHandler getDrops() { switch (getType()) { case CRAFTING: return new CombinedInvWrapper(filter, new InvWrapper(matrix)); case PATTERN: return new CombinedInvWrapper(filter, patterns); default: return new CombinedInvWrapper(filter); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1262"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package io.cattle.platform.configitem.context.dao.impl; import static io.cattle.platform.core.model.tables.HostIpAddressMapTable.*; import static io.cattle.platform.core.model.tables.HostTable.*; import static io.cattle.platform.core.model.tables.InstanceHostMapTable.*; import static io.cattle.platform.core.model.tables.InstanceTable.*; import static io.cattle.platform.core.model.tables.IpAddressNicMapTable.*; import static io.cattle.platform.core.model.tables.IpAddressTable.*; import static io.cattle.platform.core.model.tables.NetworkTable.*; import static io.cattle.platform.core.model.tables.NicTable.*; import static io.cattle.platform.core.model.tables.ServiceExposeMapTable.*; import io.cattle.platform.configitem.context.dao.DnsInfoDao; import io.cattle.platform.configitem.context.dao.MetaDataInfoDao; import io.cattle.platform.configitem.context.data.metadata.common.ContainerMetaData; import io.cattle.platform.configitem.context.data.metadata.common.HostMetaData; import io.cattle.platform.configitem.context.data.metadata.common.NetworkMetaData; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.constants.InstanceConstants; import io.cattle.platform.core.constants.IpAddressConstants; import io.cattle.platform.core.constants.ServiceConstants; import io.cattle.platform.core.dao.InstanceDao; import io.cattle.platform.core.model.Host; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.IpAddress; import io.cattle.platform.core.model.Network; import io.cattle.platform.core.model.Nic; import io.cattle.platform.core.model.ServiceExposeMap; import io.cattle.platform.core.model.tables.HostTable; import io.cattle.platform.core.model.tables.InstanceTable; import io.cattle.platform.core.model.tables.IpAddressTable; import io.cattle.platform.core.model.tables.NetworkTable; import io.cattle.platform.core.model.tables.NicTable; import io.cattle.platform.core.model.tables.ServiceExposeMapTable; import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao; import io.cattle.platform.db.jooq.mapper.MultiRecordMapper; import io.cattle.platform.object.util.DataAccessor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.jooq.JoinType; import org.jooq.Record1; import org.jooq.RecordHandler; public class MetaDataInfoDaoImpl extends AbstractJooqDao implements MetaDataInfoDao { @Inject DnsInfoDao dnsInfoDao; @Inject InstanceDao instanceDao; @Override public List<ContainerMetaData> getContainersData(long accountId) { final Map<Long, IpAddress> instanceIdToHostIpMap = dnsInfoDao .getInstanceWithHostNetworkingToIpMap(accountId); final Map<Long, HostMetaData> hostIdToHostMetadata = getHostIdToHostMetadata(accountId); MultiRecordMapper<ContainerMetaData> mapper = new MultiRecordMapper<ContainerMetaData>() { @Override protected ContainerMetaData map(List<Object> input) { ContainerMetaData data = new ContainerMetaData(); Instance instance = (Instance) input.get(0); instance.setData(instanceDao.getCacheInstanceData(instance.getId())); ServiceExposeMap serviceMap = input.get(1) != null ? (ServiceExposeMap) input.get(1) : null; String serviceIndex = DataAccessor.fieldString(instance, InstanceConstants.FIELD_SERVICE_INSTANCE_SERVICE_INDEX); Host host = null; if (input.get(2) != null) { host = (Host) input.get(2); } String primaryIp = null; if (input.get(3) != null) { primaryIp = ((IpAddress) input.get(3)).getAddress(); } if (instanceIdToHostIpMap != null && instanceIdToHostIpMap.containsKey(instance.getId())) { data.setIp(instanceIdToHostIpMap.get(instance.getId()).getAddress()); } else { data.setIp(primaryIp); } if (host != null) { HostMetaData hostMetaData = hostIdToHostMetadata.get(host.getId()); data.setInstanceAndHostMetadata(instance, hostMetaData); } data.setExposeMap(serviceMap); data.setService_index(serviceIndex); Nic nic = null; if (input.get(4) != null) { nic = (Nic) input.get(4); data.setNicInformation(nic); } Network ntwk = null; if (input.get(5) != null) { ntwk = (Network) input.get(5); data.setNetwork_uuid(ntwk.getUuid()); } return data; } }; InstanceTable instance = mapper.add(INSTANCE, INSTANCE.UUID, INSTANCE.NAME, INSTANCE.CREATE_INDEX, INSTANCE.HEALTH_STATE, INSTANCE.START_COUNT, INSTANCE.STATE, INSTANCE.EXTERNAL_ID, INSTANCE.MEMORY_RESERVATION, INSTANCE.MILLI_CPU_RESERVATION); ServiceExposeMapTable exposeMap = mapper.add(SERVICE_EXPOSE_MAP, SERVICE_EXPOSE_MAP.SERVICE_ID, SERVICE_EXPOSE_MAP.DNS_PREFIX, SERVICE_EXPOSE_MAP.UPGRADE); HostTable host = mapper.add(HOST, HOST.ID); IpAddressTable instanceIpAddress = mapper.add(IP_ADDRESS, IP_ADDRESS.ADDRESS); NicTable nic = mapper.add(NIC, NIC.ID, NIC.INSTANCE_ID, NIC.MAC_ADDRESS); NetworkTable ntwk = mapper.add(NETWORK, NETWORK.UUID); return create() .select(mapper.fields()) .from(instance) .join(INSTANCE_HOST_MAP) .on(instance.ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID)) .join(host) .on(host.ID.eq(INSTANCE_HOST_MAP.HOST_ID)) .join(exposeMap, JoinType.LEFT_OUTER_JOIN) .on(exposeMap.INSTANCE_ID.eq(instance.ID)) .join(nic) .on(nic.INSTANCE_ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID)) .join(IP_ADDRESS_NIC_MAP) .on(IP_ADDRESS_NIC_MAP.NIC_ID.eq(nic.ID)) .join(instanceIpAddress) .on(instanceIpAddress.ID.eq(IP_ADDRESS_NIC_MAP.IP_ADDRESS_ID)) .join(ntwk) .on(nic.NETWORK_ID.eq(ntwk.ID)) .where(instance.ACCOUNT_ID.eq(accountId)) .and(instance.REMOVED.isNull()) .and(instance.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED)) .and(exposeMap.REMOVED.isNull()) .and(instanceIpAddress.ROLE.eq(IpAddressConstants.ROLE_PRIMARY)) .and(ntwk.REMOVED.isNull()) .and((host.REMOVED.isNull())) .and(exposeMap.STATE.isNull().or( exposeMap.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED))) .and(exposeMap.UPGRADE.isNull().or(exposeMap.UPGRADE.eq(false))) .fetch().map(mapper); } @Override public List<String> getPrimaryIpsOnInstanceHost(final long hostId) { final List<String> ips = new ArrayList<>(); create().select(IP_ADDRESS.ADDRESS) .from(IP_ADDRESS) .join(IP_ADDRESS_NIC_MAP) .on(IP_ADDRESS.ID.eq(IP_ADDRESS_NIC_MAP.IP_ADDRESS_ID)) .join(NIC) .on(NIC.ID.eq(IP_ADDRESS_NIC_MAP.NIC_ID)) .join(INSTANCE_HOST_MAP) .on(INSTANCE_HOST_MAP.INSTANCE_ID.eq(NIC.INSTANCE_ID)) .where(INSTANCE_HOST_MAP.HOST_ID.eq(hostId) .and(NIC.REMOVED.isNull()) .and(IP_ADDRESS_NIC_MAP.REMOVED.isNull()) .and(IP_ADDRESS.REMOVED.isNull()) .and(IP_ADDRESS.ROLE.eq(IpAddressConstants.ROLE_PRIMARY)) ) .fetchInto(new RecordHandler<Record1<String>>() { @Override public void next(Record1<String> record) { ips.add(record.value1()); } }); return ips; } @Override public Map<Long, HostMetaData> getHostIdToHostMetadata(long accountId) { Map<Long, HostMetaData> toReturn = new HashMap<>(); List<HostMetaData> hosts = getAllInstanceHostMetaData(accountId); for (HostMetaData host : hosts) { toReturn.put(host.getHostId(), host); } return toReturn; } protected List<HostMetaData> getAllInstanceHostMetaData(long accountId) { MultiRecordMapper<HostMetaData> mapper = new MultiRecordMapper<HostMetaData>() { @Override protected HostMetaData map(List<Object> input) { Host host = (Host)input.get(0); IpAddress hostIp = (IpAddress)input.get(1); HostMetaData data = new HostMetaData(hostIp.getAddress(), host); return data; } }; HostTable host = mapper.add(HOST); IpAddressTable hostIpAddress = mapper.add(IP_ADDRESS); return create() .select(mapper.fields()) .from(hostIpAddress) .join(HOST_IP_ADDRESS_MAP) .on(HOST_IP_ADDRESS_MAP.IP_ADDRESS_ID.eq(hostIpAddress.ID)) .join(host) .on(host.ID.eq(HOST_IP_ADDRESS_MAP.HOST_ID)) .where(host.REMOVED.isNull()) .and(host.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED)) .and(hostIpAddress.REMOVED.isNull()) .and(host.ACCOUNT_ID.eq(accountId)) .fetch().map(mapper); } @Override public List<HostMetaData> getInstanceHostMetaData(long accountId, long instanceId) { MultiRecordMapper<HostMetaData> mapper = new MultiRecordMapper<HostMetaData>() { @Override protected HostMetaData map(List<Object> input) { Host host = (Host) input.get(0); IpAddress hostIp = (IpAddress) input.get(1); HostMetaData data = new HostMetaData(hostIp.getAddress(), host); return data; } }; HostTable host = mapper.add(HOST); IpAddressTable hostIpAddress = mapper.add(IP_ADDRESS); return create() .select(mapper.fields()) .from(hostIpAddress) .join(HOST_IP_ADDRESS_MAP) .on(HOST_IP_ADDRESS_MAP.IP_ADDRESS_ID.eq(hostIpAddress.ID)) .join(host) .on(host.ID.eq(HOST_IP_ADDRESS_MAP.HOST_ID)) .join(INSTANCE_HOST_MAP) .on(host.ID.eq(INSTANCE_HOST_MAP.HOST_ID)) .where(host.REMOVED.isNull()) .and(host.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED)) .and(INSTANCE_HOST_MAP.INSTANCE_ID.eq(instanceId)) .and(hostIpAddress.REMOVED.isNull()) .and(host.ACCOUNT_ID.eq(accountId)) .fetch().map(mapper); } @Override public List<NetworkMetaData> getNetworksMetaData(long accountId) { MultiRecordMapper<NetworkMetaData> mapper = new MultiRecordMapper<NetworkMetaData>() { @Override protected NetworkMetaData map(List<Object> input) { Network ntwk = (Network) input.get(0); Map<String, Object> meta = DataAccessor.fieldMap(ntwk, ServiceConstants.FIELD_METADATA); NetworkMetaData data = new NetworkMetaData(ntwk.getName(), ntwk.getUuid(), meta); return data; } }; NetworkTable ntwk = mapper.add(NETWORK, NETWORK.NAME, NETWORK.UUID, NETWORK.DATA); return create() .select(mapper.fields()) .from(ntwk) .where(ntwk.REMOVED.isNull()) .and(ntwk.ACCOUNT_ID.eq(accountId)) .fetch().map(mapper); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1263"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.royalrangers.controller.achievement; import com.dropbox.core.DbxException; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.achievement.AchievementRequestDto; import com.royalrangers.enums.ImageType; import com.royalrangers.service.DropboxService; import com.royalrangers.service.achievement.QuarterAchievementService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @Slf4j @RestController @RequestMapping("/achievements/quarter") public class QuarterAchievementController { @Autowired private QuarterAchievementService quarterAchievementService; @Autowired private DropboxService dropboxService; @GetMapping @ApiOperation(value = "Get all quarter achievements") public ResponseResult getAllQuarterAchievement() { try { return ResponseBuilder.success(quarterAchievementService.getAllQuarterAchievement()); } catch (Exception ex) { log.error(ex.getMessage()); return ResponseBuilder.fail("Failed added QuarterAchievement"); } } @ApiOperation(value = "Add quarter achievement related to year achievement (upLevelId)") @PostMapping public ResponseResult addQuarterAchievement(@RequestBody AchievementRequestDto params) { try { quarterAchievementService.addQuarterAchievement(params); return ResponseBuilder.success("Adding QuarterAchievement was a success"); } catch (Exception ex) { log.error(ex.getMessage()); return ResponseBuilder.fail("Failed added QuarterAchievement"); } } @GetMapping("/{quarterId}") @ApiOperation(value = "Get quarter achievement by id") public ResponseResult getQuarterAchievementById(@PathVariable Long quarterId) { try { return ResponseBuilder.success(quarterAchievementService.getQuarterAchievementById(quarterId)); } catch (Exception ex) { log.error(ex.getMessage()); return ResponseBuilder.fail("Failed get QuarterAchievement by id"); } } @DeleteMapping("/{quarterId}") @ApiOperation(value = "Delete quarter achievement by id") public ResponseResult deleteQuarterAchievement(@PathVariable Long quarterId) { try { quarterAchievementService.deleteQuarterAchievement(quarterId); return ResponseBuilder.success("Delete QuarterAchievement was a success"); } catch (Exception ex) { log.error(ex.getMessage()); return ResponseBuilder.fail("Failed deleted QuarterAchievement"); } } @PutMapping("/{quarterId}") @ApiOperation(value = "Update quarter achievement by id") public ResponseResult editQuarterAchievement(@RequestBody AchievementRequestDto params, @PathVariable Long quarterId) { try { return ResponseBuilder.success(quarterAchievementService.editQuarterAchievement(params, quarterId)); } catch (Exception ex) { log.error(ex.getMessage()); return ResponseBuilder.fail("Failed edit QuarterAchievement"); } } @PostMapping("/logo") @ApiOperation(value = "Upload and set quarter achievement logo") public ResponseResult uploadLogo(@RequestParam("quarterId") Long quarterId, @RequestParam("file") MultipartFile file) { try { String logoUrl = dropboxService.imageUpload(file, ImageType.QUARTER_ACHIEVEMENT_LOGO); quarterAchievementService.setLogoUrl(logoUrl, quarterId); return ResponseBuilder.success("LogoUrl", logoUrl); } catch (IOException | DbxException e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping("/logo") @ApiOperation(value = "Delete quarter achievement logo") public ResponseResult delete(@RequestParam("quarterId") Long quarterId) { try { quarterAchievementService.deleteLogo(quarterId); return ResponseBuilder.success("Logo deleted."); } catch (DbxException e) { return ResponseBuilder.fail(e.getMessage()); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1264"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.yahoo.sketches.pig.tuple; import com.yahoo.memory.Memory; import com.yahoo.sketches.tuple.ArrayOfDoublesSketch; import com.yahoo.sketches.tuple.ArrayOfDoublesSketches; import java.io.IOException; import org.apache.commons.math3.stat.inference.TTest; import org.apache.commons.math3.stat.StatUtils; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; /** * Calculate p-values given two ArrayOfDoublesSketch. Each value in the sketch * is treated as a separate metric measurement, and a p-value will be generated * for each metric. * * The t-statistic is calculated as follows: t = (m1 - m2) / sqrt(var1/n1 + var2/n2) * * Degrees of freedom is approximated by Welch-Satterthwaite. */ public class ArrayOfDoublesSketchesToPValueEstimates extends EvalFunc<Tuple> { @Override public Tuple exec(final Tuple input) throws IOException { if ((input == null) || (input.size() != 2)) { return null; } // Get the two sketches final DataByteArray dbaA = (DataByteArray) input.get(0); final DataByteArray dbaB = (DataByteArray) input.get(1); final ArrayOfDoublesSketch sketchA = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dbaA.get())); final ArrayOfDoublesSketch sketchB = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dbaB.get())); // Check that the size of the arrays in the sketches are the same if (sketchA.getNumValues() != sketchB.getNumValues()) { throw new IllegalArgumentException("Both sketches must have the same number of values"); } // Check if either sketch is empty if (sketchA.isEmpty() || sketchB.isEmpty()) { return null; } // Check that each sketch has at least 2 values if (sketchA.getRetainedEntries() < 2 || sketchB.getRetainedEntries() < 2) { return null; } // Get the values from each sketch double[][] valuesA = sketchA.getValues(); double[][] valuesB = sketchB.getValues(); valuesA = rotateMatrix(valuesA); valuesB = rotateMatrix(valuesB); // Calculate the p-values double[] pValues = new double[valuesA.length]; TTestWithSketch tTest = new TTestWithSketch(); for (int i = 0; i < valuesA.length; i++) { // Do some special math to get an accurate mean from the sketches // Take the sum of the values, divide by theta, then divide by the // estimate number of records. double meanA = (StatUtils.sum(valuesA[i]) / sketchA.getTheta()) / sketchA.getEstimate(); double meanB = (StatUtils.sum(valuesB[i]) / sketchB.getTheta()) / sketchB.getEstimate(); // Variance is based only on the samples we have in the tuple sketch double varianceA = StatUtils.variance(valuesA[i]); double varianceB = StatUtils.variance(valuesB[i]); // Use the estimated number of uniques double numA = sketchA.getEstimate(); double numB = sketchB.getEstimate(); pValues[i] = tTest.callTTest(meanA, meanB, varianceA, varianceB, numA, numB); } return Util.doubleArrayToTuple(pValues); } /** * Perform a clockwise rotation the output values from the tuple sketch. * * @param m Input matrix to rotate * @return Rotated matrix */ private static double[][] rotateMatrix(double[][] m) { final int width = m.length; final int height = m[0].length; double[][] result = new double[height][width]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { result[j][width - 1 - i] = m[i][j]; } } return result; } /** * This class exists to get around the protected tTest method. */ private class TTestWithSketch extends TTest { /** * Call the protected tTest method. */ public double callTTest(double m1, double m2, double v1, double v2, double n1, double n2) { return super.tTest(m1, m2, v1, v2, n1, n2); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1265"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.phenotips.data.internal; import org.phenotips.Constants; import org.xwiki.component.annotation.Component; import org.xwiki.model.EntityType; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.DocumentReferenceResolver; import org.xwiki.model.reference.EntityReference; import org.xwiki.model.reference.EntityReferenceSerializer; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.commons.lang3.StringUtils; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.LargeStringProperty; import com.xpn.xwiki.objects.StringProperty; import com.xpn.xwiki.store.XWikiHibernateBaseStore.HibernateCallback; import com.xpn.xwiki.store.XWikiHibernateStore; import com.xpn.xwiki.store.migration.DataMigrationException; import com.xpn.xwiki.store.migration.XWikiDBVersion; import com.xpn.xwiki.store.migration.hibernate.AbstractHibernateDataMigration; /** * Migration for PhenoTips issue #1280: automatically migrate old candidate, rejected and solved genes to the new * unified genes data structure. * <ul> * <li>For each {@code InvestigationClass} object create a new {@code GeneClass} object, copying the {@code gene} and * {@code comments}) fields, and set the {@code status} as "candidate".</li> * <li>For each {@code RejectedGenesClass} object create a new {@code GeneClass} object, copying the {@code gene} and * {@code comments}) fields, and set the {@code status} as "rejected".</li> * <li>If the {@code PatientClass} has a non-empty {@code solved__gene_id} property, create a new {@code GeneClass} * object, copying the {@code gene} field, and set the {@code status} as "solved".</li> * <li>Successfully migrated objects are removed.</li> * </ul> * * @version $Id$ * @since 1.3M1 */ @Component @Named("R71490PhenoTips#1280") @Singleton public class R71490PhenoTips1280DataMigration extends AbstractHibernateDataMigration implements HibernateCallback<Object> { private static final String GENE_NAME = "gene"; private static final String COMMENTS_NAME = "comments"; private static final String SOLVED_NAME = "solved__gene_id"; private static final String STATUS_NAME = "status"; private static final String OR = "' or o.className = '"; private static final EntityReference PATIENT_CLASS = new EntityReference("PatientClass", EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE); private static final EntityReference INVESTIGATION_CLASS = new EntityReference("InvestigationClass", EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE); private static final EntityReference GENE_CLASS = new EntityReference("GeneClass", EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE); private static final EntityReference REJECTED_CLASS = new EntityReference("RejectedGenesClass", EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE); /** Resolves unprefixed document names to the current wiki. */ @Inject @Named("current") private DocumentReferenceResolver<String> resolver; /** Serializes the class name without the wiki prefix, to be used in the database query. */ @Inject @Named("compactwiki") private EntityReferenceSerializer<String> serializer; /** Resolves class names to the current wiki. */ @Inject @Named("current") private DocumentReferenceResolver<EntityReference> entityResolver; @Override public String getDescription() { return "Migrate all existing gene values to the GeneClass objects"; } @Override public XWikiDBVersion getVersion() { return new XWikiDBVersion(71490); } @Override public void hibernateMigrate() throws DataMigrationException, XWikiException { getStore().executeWrite(getXWikiContext(), this); } @Override public Object doInHibernate(Session session) throws HibernateException, XWikiException { XWikiContext context = getXWikiContext(); XWiki xwiki = context.getWiki(); DocumentReference patientClassReference = this.entityResolver.resolve(PATIENT_CLASS); DocumentReference investigationClassReference = this.entityResolver.resolve(INVESTIGATION_CLASS); DocumentReference geneClassReference = this.entityResolver.resolve(GENE_CLASS); DocumentReference rejectedGenesClassReference = this.entityResolver.resolve(REJECTED_CLASS); Query q = session.createQuery("select distinct o.name from BaseObject o where o.className = '" + this.serializer.serialize(investigationClassReference) + OR + this.serializer.serialize(rejectedGenesClassReference) + OR + this.serializer.serialize(patientClassReference) + "' and exists(from StringProperty p where p.id.id = o.id and p.id.name = '" + SOLVED_NAME + "' and p.value <> '')"); @SuppressWarnings("unchecked") List<String> docs = q.list(); for (String docName : docs) { XWikiDocument doc = xwiki.getDocument(this.resolver.resolve(docName), context); List<String> geneList = new ArrayList<>(); migrateSolvedGenes(doc, patientClassReference, geneClassReference, context, geneList); migrateGenes(doc, rejectedGenesClassReference, geneClassReference, context, geneList, "rejected"); migrateGenes(doc, investigationClassReference, geneClassReference, context, geneList, "candidate"); doc.setComment("Migrate old candidate/rejected/solved genes to GeneClass objects"); doc.setMinorEdit(true); try { // There's a bug in XWiki which prevents saving an object in the same session that it was loaded, // so we must clear the session cache first. session.clear(); ((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, false); session.flush(); } catch (DataMigrationException e) { } } return null; } private void migrateSolvedGenes(XWikiDocument doc, DocumentReference patientClassReference, DocumentReference geneClassReference, XWikiContext context, List<String> geneList) throws HibernateException, XWikiException { BaseObject patient = doc.getXObject(patientClassReference); StringProperty oldTarget = (StringProperty) patient.get(SOLVED_NAME); if (oldTarget == null) { return; } patient.removeField(SOLVED_NAME); String geneName = oldTarget.getValue(); if (!StringUtils.isBlank(geneName)) { BaseObject gene = doc.newXObject(geneClassReference, context); gene.setStringValue(GENE_NAME, geneName); gene.setStringValue(STATUS_NAME, "solved"); geneList.add(geneName); } } private void migrateGenes(XWikiDocument doc, DocumentReference oldGenesClassReference, DocumentReference geneClassReference, XWikiContext context, List<String> geneList, String status) throws HibernateException, XWikiException { List<BaseObject> genes = doc.getXObjects(oldGenesClassReference); if (genes == null || genes.isEmpty()) { return; } for (BaseObject gene : genes) { if (gene == null) { continue; } StringProperty oldGeneNameProp = (StringProperty) gene.get(GENE_NAME); if (oldGeneNameProp == null || StringUtils.isBlank(oldGeneNameProp.getValue())) { continue; } String geneName = oldGeneNameProp.getValue(); LargeStringProperty oldGeneCommentsProp = (LargeStringProperty) gene.get(COMMENTS_NAME); String geneComments = null; if (oldGeneCommentsProp != null && !StringUtils.isBlank(oldGeneCommentsProp.getValue())) { geneComments = oldGeneCommentsProp.getValue(); } // check if we already have migrated this gene if (!geneList.contains(geneName)) { BaseObject newgene = doc.newXObject(geneClassReference, context); newgene.setStringValue(GENE_NAME, geneName); newgene.setStringValue(STATUS_NAME, status); if (geneComments != null) { newgene.setLargeStringValue(COMMENTS_NAME, geneComments); } geneList.add(geneName); } else if (geneComments != null) { String commentUpend = "\nAutomatic migration: gene was duplicated in the " + status + " gene section."; commentUpend += "\nOriginal comment: \n" + geneComments; updateComment(geneName, doc, commentUpend, geneClassReference); } } doc.removeXObjects(oldGenesClassReference); } private void updateComment(String geneName, XWikiDocument doc, String commentUpend, DocumentReference geneClassReference) throws HibernateException, XWikiException { List<BaseObject> genes = doc.getXObjects(geneClassReference); for (BaseObject gene : genes) { if (gene == null) { continue; } StringProperty geneNameProp = (StringProperty) gene.get(GENE_NAME); if (geneNameProp != null && geneNameProp.getValue().equals(geneName)) { LargeStringProperty oldGeneCommentsProp = (LargeStringProperty) gene.get(COMMENTS_NAME); if (oldGeneCommentsProp == null) { gene.setLargeStringValue(COMMENTS_NAME, commentUpend); } else { gene.setLargeStringValue(COMMENTS_NAME, oldGeneCommentsProp.getValue() + commentUpend); } } } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1266"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package io.github.lukehutch.fastclasspathscanner.scanner; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import io.github.lukehutch.fastclasspathscanner.scanner.ClasspathElement.ClasspathResource.ClasspathResourceInZipFile; import io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.FileMatchProcessorWrapper; import io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.FilePathTesterAndMatchProcessorWrapper; import io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.ScanSpecPathMatch; import io.github.lukehutch.fastclasspathscanner.utils.FastManifestParser; import io.github.lukehutch.fastclasspathscanner.utils.FastPathResolver; import io.github.lukehutch.fastclasspathscanner.utils.InterruptionChecker; import io.github.lukehutch.fastclasspathscanner.utils.LogNode; import io.github.lukehutch.fastclasspathscanner.utils.MultiMapKeyToList; import io.github.lukehutch.fastclasspathscanner.utils.Recycler; import io.github.lukehutch.fastclasspathscanner.utils.WorkQueue; /** A zip/jarfile classpath element. */ class ClasspathElementZip extends ClasspathElement { /** * ZipFile recycler -- creates one ZipFile per thread that wants to concurrently access this classpath element. */ private Recycler<ZipFile, IOException> zipFileRecycler; /** Result of parsing the manifest file for this jarfile. */ private FastManifestParser fastManifestParser; /** A zip/jarfile classpath element. */ ClasspathElementZip(final ClasspathRelativePath classpathElt, final ScanSpec scanSpec, final boolean scanFiles, final InterruptionChecker interruptionChecker, final WorkQueue<ClasspathRelativePath> workQueue, final LogNode log) { super(classpathElt, scanSpec, scanFiles, interruptionChecker, log); final File classpathEltFile; try { classpathEltFile = classpathElt.getFile(); } catch (final IOException e) { if (log != null) { log.log("Exception while trying to canonicalize path " + classpathElt.getResolvedPath(), e); } ioExceptionOnOpen = true; return; } zipFileRecycler = new Recycler<ZipFile, IOException>() { @Override public ZipFile newInstance() throws IOException { return new ZipFile(classpathEltFile); } }; ZipFile zipFile = null; try { try { zipFile = zipFileRecycler.acquire(); } catch (final IOException e) { if (log != null) { log.log("Exception opening zipfile " + classpathEltFile, e); } ioExceptionOnOpen = true; return; } if (!scanFiles) { // If not performing a scan, just get the manifest entry manually fastManifestParser = new FastManifestParser(zipFile, zipFile.getEntry("META-INF/MANIFEST.MF"), log); } else { // Scan for path matches within jarfile, and record ZipEntry objects of matching files. // Will parse the manifest file if it finds it. final int numEntries = zipFile.size(); fileMatches = new MultiMapKeyToList<>(); classfileMatches = new ArrayList<>(numEntries); fileToLastModified = new HashMap<>(); scanZipFile(classpathEltFile, zipFile, log); } if (fastManifestParser != null && fastManifestParser.classPath != null) { // Get the classpath elements from the Class-Path manifest entry // (these are space-delimited). final String[] manifestClassPathElts = fastManifestParser.classPath.split(" "); // Class-Path entries in the manifest file are resolved relative to // the dir the manifest's jarfile is contaiin. Get the parent path. final String pathOfContainingDir = FastPathResolver.resolve(classpathEltFile.getParent()); // Create child classpath elements from Class-Path entry childClasspathElts = new ArrayList<>(manifestClassPathElts.length); for (int i = 0; i < manifestClassPathElts.length; i++) { final String manifestClassPathElt = manifestClassPathElts[i]; if (!manifestClassPathElt.isEmpty()) { ClasspathRelativePath childRelativePath = new ClasspathRelativePath(pathOfContainingDir, manifestClassPathElt); childClasspathElts.add(childRelativePath); if (log != null) { log.log("Found Class-Path entry in manifest: " + manifestClassPathElt + " -> " + childRelativePath); } } } // Schedule child classpath elements for scanning workQueue.addWorkUnits(childClasspathElts); } } finally { zipFileRecycler.release(zipFile); } } /** Scan a zipfile for file path patterns matching the scan spec. */ private void scanZipFile(final File zipFileFile, final ZipFile zipFile, final LogNode log) { String prevParentRelativePath = null; ScanSpecPathMatch prevParentMatchStatus = null; int entryIdx = 0; for (final Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries.hasMoreElements();) { if ((entryIdx++ & 0x3ff) == 0) { if (interruptionChecker.checkAndReturn()) { return; } } final ZipEntry zipEntry = entries.nextElement(); String relativePath = zipEntry.getName(); if (relativePath.startsWith("/")) { // Shouldn't happen with the standard Java zipfile implementation (but just to be safe) relativePath = relativePath.substring(1); } // Ignore directory entries, they are not needed final boolean isDir = zipEntry.isDirectory(); if (isDir) { continue; } // Get match status of the parent directory if this zipentry file's relative path // (or reuse the last match status for speed, if the directory name hasn't changed). final int lastSlashIdx = relativePath.lastIndexOf("/"); final String parentRelativePath = lastSlashIdx < 0 ? "/" : relativePath.substring(0, lastSlashIdx + 1); final boolean parentRelativePathChanged = !parentRelativePath.equals(prevParentRelativePath); final ScanSpecPathMatch parentMatchStatus = prevParentRelativePath == null || parentRelativePathChanged ? scanSpec.pathWhitelistMatchStatus(parentRelativePath) : prevParentMatchStatus; prevParentRelativePath = parentRelativePath; prevParentMatchStatus = parentMatchStatus; // Store entry for manifest file, if present, so that the entry doesn't have to be looked up by name if (relativePath.equalsIgnoreCase("META-INF/MANIFEST.MF")) { if (log != null) { log.log("Found manifest file: " + relativePath); } fastManifestParser = new FastManifestParser(zipFile, zipEntry, log); } // Class can only be scanned if it's within a whitelisted path subtree, or if it is a classfile // that has been specifically-whitelisted if (parentMatchStatus != ScanSpecPathMatch.WITHIN_WHITELISTED_PATH && (parentMatchStatus != ScanSpecPathMatch.AT_WHITELISTED_CLASS_PACKAGE || !scanSpec.isSpecificallyWhitelistedClass(relativePath))) { continue; } if (log != null) { log.log("Found whitelisted file in jarfile: " + relativePath); } // Store relative paths of any classfiles encountered if (ClasspathRelativePath.isClassfile(relativePath)) { classfileMatches.add(new ClasspathResourceInZipFile(zipFileFile, relativePath, zipEntry)); } // Match file paths against path patterns for (final FilePathTesterAndMatchProcessorWrapper fileMatcher : scanSpec.getFilePathTestersAndMatchProcessorWrappers()) { if (fileMatcher.filePathMatches(zipFileFile, relativePath, log)) { // File's relative path matches. // Don't use the last modified time from the individual zipEntry objects, // we use the last modified time for the zipfile itself instead. fileMatches.put(fileMatcher.fileMatchProcessorWrapper, new ClasspathResourceInZipFile(zipFileFile, relativePath, zipEntry)); } } } fileToLastModified.put(zipFileFile, zipFileFile.lastModified()); } /** * Open an input stream and call a FileMatchProcessor on a specific whitelisted match found within this zipfile. */ @Override protected void openInputStreamAndProcessFileMatch(final ClasspathResource fileMatchResource, final FileMatchProcessorWrapper fileMatchProcessorWrapper) throws IOException { if (!ioExceptionOnOpen) { // Open InputStream on relative path within zipfile ZipFile zipFile = null; try { zipFile = zipFileRecycler.acquire(); final ZipEntry zipEntry = ((ClasspathResourceInZipFile) fileMatchResource).zipEntry; try (InputStream inputStream = zipFile.getInputStream(zipEntry)) { // Run FileMatcher fileMatchProcessorWrapper.processMatch(fileMatchResource.classpathEltFile, fileMatchResource.relativePath, inputStream, zipEntry.getSize()); } } finally { zipFileRecycler.release(zipFile); } } } /** Open an input stream and parse a specific classfile found within this zipfile. */ @Override protected void openInputStreamAndParseClassfile(final ClasspathResource classfileResource, final ClassfileBinaryParser classfileBinaryParser, final ScanSpec scanSpec, final ConcurrentHashMap<String, String> stringInternMap, final ConcurrentLinkedQueue<ClassInfoUnlinked> classInfoUnlinked, final LogNode log) throws InterruptedException, IOException { if (!ioExceptionOnOpen) { ZipFile zipFile = null; try { zipFile = zipFileRecycler.acquire(); final ZipEntry zipEntry = ((ClasspathResourceInZipFile) classfileResource).zipEntry; try (InputStream inputStream = zipFile.getInputStream(zipEntry)) { // Parse classpath binary format, creating a ClassInfoUnlinked object final ClassInfoUnlinked thisClassInfoUnlinked = classfileBinaryParser .readClassInfoFromClassfileHeader(classfileResource.relativePath, inputStream, scanSpec, stringInternMap, log); // If class was successfully read, output new ClassInfoUnlinked object if (thisClassInfoUnlinked != null) { classInfoUnlinked.add(thisClassInfoUnlinked); thisClassInfoUnlinked.logTo(log); } } } finally { zipFileRecycler.release(zipFile); } } } /** Close all open ZipFiles. */ @Override public void close() { if (zipFileRecycler != null) { zipFileRecycler.close(); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1267"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.jboss.as.controller.remote; import static java.security.AccessController.doPrivileged; import static org.jboss.as.controller.logging.ControllerLogger.MGMT_OP_LOGGER; import java.security.PrivilegedAction; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.jboss.as.controller.ModelController; import org.jboss.as.protocol.mgmt.support.ManagementChannelInitialization; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.jboss.threads.EnhancedQueueExecutor; import org.jboss.threads.JBossThreadFactory; /** * Service used to create operation handlers per incoming channel * * @author <a href="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="513a303338237f3a39303f113b333e22227f323e3c">[email protected]</a>">Kabir Khan</a> */ public abstract class AbstractModelControllerOperationHandlerFactoryService implements Service<AbstractModelControllerOperationHandlerFactoryService>, ManagementChannelInitialization { public static final ServiceName OPERATION_HANDLER_NAME_SUFFIX = ServiceName.of("operation", "handler"); // The defaults if no executor was defined private static final int WORK_QUEUE_SIZE = 512; private static final int POOL_CORE_SIZE = 4; private static final int POOL_MAX_SIZE = 4; private final InjectedValue<ModelController> modelControllerValue = new InjectedValue<ModelController>(); private final InjectedValue<ExecutorService> executor = new InjectedValue<ExecutorService>(); private final InjectedValue<ScheduledExecutorService> scheduledExecutor = new InjectedValue<>(); private ResponseAttachmentInputStreamSupport responseAttachmentSupport; private ExecutorService clientRequestExecutor; /** * Use to inject the model controller that will be the target of the operations * * @return the injected value holder */ public InjectedValue<ModelController> getModelControllerInjector() { return modelControllerValue; } public InjectedValue<ExecutorService> getExecutorInjector() { return executor; } public InjectedValue<ScheduledExecutorService> getScheduledExecutorInjector() { return scheduledExecutor; } /** {@inheritDoc} */ @Override public synchronized void start(StartContext context) throws StartException { MGMT_OP_LOGGER.debugf("Starting operation handler service %s", context.getController().getName()); responseAttachmentSupport = new ResponseAttachmentInputStreamSupport(scheduledExecutor.getValue()); final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<JBossThreadFactory>() { public JBossThreadFactory run() { return new JBossThreadFactory(new ThreadGroup("management-handler-thread"), Boolean.FALSE, null, "%G - %t", null, null); } }); if (EnhancedQueueExecutor.DISABLE_HINT) { ThreadPoolExecutor executor = new ThreadPoolExecutor(POOL_CORE_SIZE, POOL_MAX_SIZE, 600L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(WORK_QUEUE_SIZE), threadFactory); // Allow the core threads to time out as well executor.allowCoreThreadTimeOut(true); this.clientRequestExecutor = executor; } else { this.clientRequestExecutor = new EnhancedQueueExecutor.Builder() .setCorePoolSize(POOL_CORE_SIZE) .setMaximumPoolSize(POOL_MAX_SIZE) .setKeepAliveTime(600L, TimeUnit.SECONDS) .setMaximumQueueSize(WORK_QUEUE_SIZE) .setThreadFactory(threadFactory) .allowCoreThreadTimeOut(true) .build(); } } /** {@inheritDoc} */ @Override public synchronized void stop(final StopContext stopContext) { final ExecutorService executorService = executor.getValue(); final Runnable task = new Runnable() { @Override public void run() { try { responseAttachmentSupport.shutdown(); // Shut down new requests to the client request executor, // but don't mess with currently running tasks clientRequestExecutor.shutdown(); } finally { stopContext.complete(); } } }; try { executorService.execute(task); } catch (RejectedExecutionException e) { task.run(); } finally { stopContext.asynchronous(); } } /** {@inheritDoc} */ @Override public synchronized AbstractModelControllerOperationHandlerFactoryService getValue() throws IllegalStateException { return this; } protected ModelController getController() { return modelControllerValue.getValue(); } protected ExecutorService getExecutor() { return executor.getValue(); } protected ResponseAttachmentInputStreamSupport getResponseAttachmentSupport() { return responseAttachmentSupport; } protected final ExecutorService getClientRequestExecutor() { return clientRequestExecutor; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1268"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package io.github.thatsmusic99.headsplus.commands.maincommand; import io.github.thatsmusic99.headsplus.HeadsPlus; import io.github.thatsmusic99.headsplus.api.HPPlayer; import io.github.thatsmusic99.headsplus.commands.CommandInfo; import io.github.thatsmusic99.headsplus.commands.IHeadsPlusCommand; import io.github.thatsmusic99.headsplus.config.ConfigTextMenus; import io.github.thatsmusic99.headsplus.config.HeadsPlusMessagesManager; import io.github.thatsmusic99.headsplus.util.HPUtils; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @CommandInfo( commandname = "profile", permission = "headsplus.maincommand.profile", maincommand = true, usage = "/hp profile [Player]", descriptionPath = "descriptions.hp.profile" ) public class ProfileCommand implements IHeadsPlusCommand { private String prof(OfflinePlayer p, CommandSender sender) throws SQLException { try { HPPlayer pl = HPPlayer.getHPPlayer(p); return ConfigTextMenus.ProfileTranslator.translate(pl, sender); } catch (NullPointerException ex) { ex.printStackTrace(); return HeadsPlusMessagesManager.get().getString("commands.errors.no-data", sender); } } @Override public boolean fire(String[] args, CommandSender cs) { String name = cs.getName(); if (args.length != 1) { name = args[1]; } HPUtils.getOfflinePlayer(name).thenAccept(player -> { try { if (cs instanceof Player) { if (cs.getName().equalsIgnoreCase(player.getName())) { cs.sendMessage(prof(player, cs)); } else { if (cs.hasPermission("headsplus.maincommand.profile.others")) { cs.sendMessage(prof(player, cs)); } else { HeadsPlusMessagesManager.get().sendMessage("commands.errors.no-perm", cs); } } } else { if (cs.getName().equalsIgnoreCase(player.getName())) { // Not a player cs.sendMessage(HeadsPlusMessagesManager.get().getString("commands.profile.cant-view-data")); } else { cs.sendMessage(prof(player, cs)); } } } catch (SQLException e) { DebugPrint.createReport(e, "Subcommand (profile)", true, cs); } }); return true; } @Override public boolean shouldEnable() { return true; } @Override public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) { List<String> results = new ArrayList<>(); if (args.length == 2) { StringUtil.copyPartialMatches(args[1], IHeadsPlusCommand.getPlayers(sender), results); } return results; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1269"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package net.sf.taverna.t2.workbench.reference.config; import java.util.HashMap; import java.util.Map; import net.sf.taverna.t2.workbench.configuration.AbstractConfigurable; /** * Configuration for the reference service and provenance. * * @author David Withers * @author Stuart Owen */ public class DataManagementConfiguration extends AbstractConfigurable { public static final String IN_MEMORY = "in_memory"; public static final String ENABLE_PROVENANCE = "provenance"; public static final String CONNECTOR_TYPE = "connector"; public static final String PORT = "port"; public static final String CURRENT_PORT = "current_port"; public static final String REFERENCE_SERVICE_CONTEXT = "referenceService.context"; public static final String IN_MEMORY_CONTEXT = "inMemoryReferenceServiceContext.xml"; public static final String HIBERNATE_CONTEXT = "hibernateReferenceServiceContext.xml"; public static final String HIBERNATE_DIALECT = "dialect"; public static final String START_INTERNAL_DERBY = "start_derby"; public static final String POOL_MAX_ACTIVE = "pool_max_active"; public static final String POOL_MIN_IDLE = "pool_min_idle"; public static final String POOL_MAX_IDLE = "pool_max_idle"; public static final String DRIVER_CLASS_NAME = "driver"; public static final String JDBC_URI = "jdbcuri"; public static final String USERNAME = "username"; public static final String PASSWORD = "password"; //FIXME: these should me just mysql & derby - but build & dependency issues is causing the provenance to expect these values: public static final String CONNECTOR_MYSQL="mysql"; public static final String CONNECTOR_DERBY="derby"; public static final String JNDI_NAME = "jdbc/taverna"; private Map<String, String> defaultPropertyMap; private static DataManagementConfiguration instance; public static DataManagementConfiguration getInstance() { if (instance == null) { instance = new DataManagementConfiguration(); if (instance.getStartInternalDerbyServer()) { DataManagementHelper.startDerbyNetworkServer(); } DataManagementHelper.setupDataSource(); } return instance; } public String getDatabaseContext() { if (getProperty(IN_MEMORY).equalsIgnoreCase("true")) { return IN_MEMORY_CONTEXT; } else { return HIBERNATE_CONTEXT; } } public String getDriverClassName() { return getProperty(DRIVER_CLASS_NAME); } public boolean isProvenanceEnabled() { return getProperty(ENABLE_PROVENANCE).equalsIgnoreCase("true"); } public boolean getStartInternalDerbyServer() { return getProperty(START_INTERNAL_DERBY).equalsIgnoreCase("true"); } public int getPort() { return Integer.valueOf(getProperty(PORT)); } public void setCurrentPort(int port) { setProperty(CURRENT_PORT, String.valueOf(port)); } public int getCurrentPort() { return Integer.valueOf(getProperty(CURRENT_PORT)); } public int getPoolMaxActive() { return Integer.valueOf(getProperty(POOL_MAX_ACTIVE)); } public int getPoolMinIdle() { return Integer.valueOf(getProperty(POOL_MIN_IDLE)); } public int getPoolMaxIdle() { return Integer.valueOf(getProperty(POOL_MAX_IDLE)); } private DataManagementConfiguration() { } public String getCategory() { return "general"; } public Map<String, String> getDefaultPropertyMap() { if (defaultPropertyMap == null) { defaultPropertyMap = new HashMap<String, String>(); defaultPropertyMap.put(IN_MEMORY, "true"); defaultPropertyMap.put(ENABLE_PROVENANCE, "true"); defaultPropertyMap.put(PORT, "1527"); //defaultPropertyMap.put(DRIVER_CLASS_NAME, "org.apache.derby.jdbc.ClientDriver"); defaultPropertyMap.put(DRIVER_CLASS_NAME, "org.apache.derby.jdbc.EmbeddedDriver"); defaultPropertyMap.put(HIBERNATE_DIALECT, "org.hibernate.dialect.DerbyDialect"); defaultPropertyMap.put(POOL_MAX_ACTIVE, "50"); defaultPropertyMap.put(POOL_MAX_IDLE, "50"); defaultPropertyMap.put(POOL_MIN_IDLE, "10"); defaultPropertyMap.put(USERNAME,""); defaultPropertyMap.put(PASSWORD,""); defaultPropertyMap.put(JDBC_URI,"jdbc:derby:t2-database;create=true;upgrade=true"); defaultPropertyMap.put(START_INTERNAL_DERBY, "false"); defaultPropertyMap.put(CONNECTOR_TYPE,CONNECTOR_DERBY); } return defaultPropertyMap; } public String getHibernateDialect() { return getProperty(HIBERNATE_DIALECT); } public String getDisplayName() { return "Data and provenance"; } public String getFilePrefix() { return "DataAndProvenance"; } public String getUUID() { return "6BD3F5C1-C68D-4893-8D9B-2F46FA1DDB19"; } public String getConnectorType() { return getProperty(CONNECTOR_TYPE); } public String getJDBCUri() { if (CONNECTOR_DERBY.equals(getConnectorType()) && getStartInternalDerbyServer()) { return "jdbc:derby://localhost:" + getCurrentPort() + "/t2-database;create=true;upgrade=true"; } else { return getProperty(JDBC_URI); } } public String getUsername() { return getProperty(USERNAME); } public String getPassword() { return getProperty(PASSWORD); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1270"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package net.finmath.montecarlo.assetderivativevaluation; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; import net.finmath.exception.CalculationException; import net.finmath.montecarlo.IndependentIncrements; import net.finmath.montecarlo.model.ProcessModel; import net.finmath.montecarlo.process.EulerSchemeFromProcessModel; import net.finmath.montecarlo.process.MonteCarloProcess; import net.finmath.stochastic.RandomVariable; import net.finmath.time.TimeDiscretization; /** * This class glues together an <code>AbstractProcessModel</code> and a Monte-Carlo implementation of a <code>MonteCarloProcessFromProcessModel</code> * and implements <code>AssetModelMonteCarloSimulationModel</code>. * * The model is specified via the object implementing <code>ProcessModel</code>. * * @author Christian Fries * @see net.finmath.montecarlo.process.MonteCarloProcess The interface for numerical schemes. * @see net.finmath.montecarlo.model.ProcessModel The interface for models provinding parameters to numerical schemes. * @version 1.0 */ public class MonteCarloAssetModel implements AssetModelMonteCarloSimulationModel { private final ProcessModel model; private final MonteCarloProcess process; /** * Create a Monte-Carlo simulation using given process discretization scheme. * * @param process The numerical scheme to be used. */ public MonteCarloAssetModel(final MonteCarloProcess process) { super(); this.model = process.getModel(); this.process = process; } /** * Create a Monte-Carlo simulation using given process discretization scheme. * * @param model The model to be used. * @param process The numerical scheme to be used. */ public MonteCarloAssetModel( final ProcessModel model, final MonteCarloProcess process) { super(); this.model = model; this.process = process; } public MonteCarloAssetModel(ProcessModel model, IndependentIncrements stochasticDriver) { super(); this.model = model; this.process = new EulerSchemeFromProcessModel(model, stochasticDriver); } @Override public RandomVariable getAssetValue(final double time, final int assetIndex) throws CalculationException { int timeIndex = getTimeIndex(time); if(timeIndex < 0) { throw new IllegalArgumentException("The model does not provide an interpolation of simulation time (time given was " + time + ")."); } return getAssetValue(timeIndex, assetIndex); } @Override public RandomVariable getAssetValue(final int timeIndex, final int assetIndex) throws CalculationException { return process.getProcessValue(timeIndex, assetIndex); } @Override public RandomVariable getNumeraire(final int timeIndex) throws CalculationException { final double time = getTime(timeIndex); // TODO Add caching of the numerare here! return model.getNumeraire(process, time); } @Override public RandomVariable getNumeraire(final double time) throws CalculationException { // TODO Add caching of the numerare here! return model.getNumeraire(process, time); } @Override public RandomVariable getMonteCarloWeights(final double time) throws CalculationException { return getMonteCarloWeights(getTimeIndex(time)); } @Override public int getNumberOfAssets() { return 1; } @Override public AssetModelMonteCarloSimulationModel getCloneWithModifiedData(final Map<String, Object> dataModified) throws CalculationException { final ProcessModel newModel = model.getCloneWithModifiedData(dataModified); MonteCarloProcess newProcess; try { final Map<String, Object> dataModifiedForProcess = new HashMap<String, Object>(); dataModifiedForProcess.putAll(dataModified); if(!dataModifiedForProcess.containsKey("model")) { dataModifiedForProcess.put("model", newModel); } newProcess = process.getCloneWithModifiedData(dataModifiedForProcess); } catch(final UnsupportedOperationException e) { newProcess = process; } // In the case where the model has changed we need a new process anyway if(newModel != model && newProcess == process) { newProcess = process.getCloneWithModifiedModel(newModel); } return new MonteCarloAssetModel(newModel, newProcess); } /** * The method is not implemented. Instead call getCloneWithModifiedData on the model * an create a new process from it. * * @param seed The new seed. */ @Override @Deprecated public AssetModelMonteCarloSimulationModel getCloneWithModifiedSeed(final int seed) { throw new UnsupportedOperationException("Method not implemented"); } @Override public int getNumberOfPaths() { return process.getNumberOfPaths(); } @Override public LocalDateTime getReferenceDate() { return model.getReferenceDate(); } @Override public TimeDiscretization getTimeDiscretization() { return process.getTimeDiscretization(); } @Override public double getTime(final int timeIndex) { return process.getTime(timeIndex); } @Override public int getTimeIndex(final double time) { return process.getTimeIndex(time); } @Override public RandomVariable getRandomVariableForConstant(final double value) { return model.getRandomVariableForConstant(value); } @Override public RandomVariable getMonteCarloWeights(final int timeIndex) throws CalculationException { return process.getMonteCarloWeights(timeIndex); } /** * Returns the {@link ProcessModel} used for this Monte-Carlo simulation. * * @return the model */ public ProcessModel getModel() { return model; } /** * Returns the {@link MonteCarloProcess} used for this Monte-Carlo simulation. * * @return the process */ public MonteCarloProcess getProcess() { return process; } @Override public String toString() { return this.getClass().getSimpleName() + " [model=" + model + "]"; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1271"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.hisp.dhis.dxf2.metadata; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hisp.dhis.common.IdentifiableObject; import org.hisp.dhis.common.SetMap; import org.hisp.dhis.commons.timer.SystemTimer; import org.hisp.dhis.commons.timer.Timer; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataelement.DataElementCategory; import org.hisp.dhis.dataelement.DataElementCategoryCombo; import org.hisp.dhis.dataelement.DataElementCategoryOption; import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo; import org.hisp.dhis.dataelement.DataElementOperand; import org.hisp.dhis.dataentryform.DataEntryForm; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.dataset.DataSetElement; import org.hisp.dhis.dataset.Section; import org.hisp.dhis.dxf2.common.OrderParams; import org.hisp.dhis.fieldfilter.FieldFilterService; import org.hisp.dhis.indicator.Indicator; import org.hisp.dhis.indicator.IndicatorType; import org.hisp.dhis.legend.Legend; import org.hisp.dhis.legend.LegendSet; import org.hisp.dhis.node.NodeUtils; import org.hisp.dhis.node.types.ComplexNode; import org.hisp.dhis.node.types.RootNode; import org.hisp.dhis.node.types.SimpleNode; import org.hisp.dhis.option.Option; import org.hisp.dhis.option.OptionSet; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramIndicator; import org.hisp.dhis.program.ProgramStage; import org.hisp.dhis.program.ProgramStageDataElement; import org.hisp.dhis.program.ProgramStageSection; import org.hisp.dhis.program.ProgramTrackedEntityAttribute; import org.hisp.dhis.programrule.ProgramRule; import org.hisp.dhis.programrule.ProgramRuleAction; import org.hisp.dhis.programrule.ProgramRuleService; import org.hisp.dhis.programrule.ProgramRuleVariable; import org.hisp.dhis.programrule.ProgramRuleVariableService; import org.hisp.dhis.query.Query; import org.hisp.dhis.query.QueryService; import org.hisp.dhis.schema.Schema; import org.hisp.dhis.schema.SchemaService; import org.hisp.dhis.system.SystemInfo; import org.hisp.dhis.system.SystemService; import org.hisp.dhis.trackedentity.TrackedEntity; import org.hisp.dhis.trackedentity.TrackedEntityAttribute; import org.hisp.dhis.user.CurrentUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Morten Olav Hansen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8d5d7caccddd6d7d0f8dfd5d9d1d496dbd7d5">[email protected]</a>> */ @Component public class DefaultMetadataExportService implements MetadataExportService { private static final Log log = LogFactory.getLog( MetadataExportService.class ); @Autowired private SchemaService schemaService; @Autowired private QueryService queryService; @Autowired private FieldFilterService fieldFilterService; @Autowired private CurrentUserService currentUserService; @Autowired private ProgramRuleService programRuleService; @Autowired private ProgramRuleVariableService programRuleVariableService; @Autowired private SystemService systemService; @Override @SuppressWarnings( "unchecked" ) public Map<Class<? extends IdentifiableObject>, List<? extends IdentifiableObject>> getMetadata( MetadataExportParams params ) { Timer timer = new SystemTimer().start(); Map<Class<? extends IdentifiableObject>, List<? extends IdentifiableObject>> metadata = new HashMap<>(); if ( params.getUser() == null ) { params.setUser( currentUserService.getCurrentUser() ); } if ( params.getClasses().isEmpty() ) { schemaService.getMetadataSchemas().stream().filter( Schema::isIdentifiableObject ) .forEach( schema -> params.getClasses().add( (Class<? extends IdentifiableObject>) schema.getKlass() ) ); } log.info( "(" + params.getUsername() + ") Export:Start" ); for ( Class<? extends IdentifiableObject> klass : params.getClasses() ) { Query query; if ( params.getQuery( klass ) != null ) { query = params.getQuery( klass ); } else { OrderParams orderParams = new OrderParams( Sets.newHashSet( params.getDefaultOrder() ) ); query = queryService.getQueryFromUrl( klass, params.getDefaultFilter(), orderParams.getOrders( schemaService.getDynamicSchema( klass ) ) ); } if ( query.getUser() == null ) { query.setUser( params.getUser() ); } query.setDefaultOrder(); List<? extends IdentifiableObject> objects = queryService.query( query ); if ( !objects.isEmpty() ) { log.info( "(" + params.getUsername() + ") Exported " + objects.size() + " objects of type " + klass.getSimpleName() ); metadata.put( klass, objects ); } } log.info( "(" + params.getUsername() + ") Export:Done took " + timer.toString() ); return metadata; } @Override public RootNode getMetadataAsNode( MetadataExportParams params ) { RootNode rootNode = NodeUtils.createMetadata(); SystemInfo systemInfo = systemService.getSystemInfo(); ComplexNode system = rootNode.addChild( new ComplexNode( "system" ) ); system.addChild( new SimpleNode( "id", systemInfo.getSystemId() ) ); system.addChild( new SimpleNode( "rev", systemInfo.getRevision() ) ); system.addChild( new SimpleNode( "version", systemInfo.getVersion() ) ); system.addChild( new SimpleNode( "date", systemInfo.getServerDate() ) ); Map<Class<? extends IdentifiableObject>, List<? extends IdentifiableObject>> metadata = getMetadata( params ); for ( Class<? extends IdentifiableObject> klass : metadata.keySet() ) { rootNode.addChild( fieldFilterService.filter( klass, metadata.get( klass ), params.getFields( klass ) ) ); } return rootNode; } @Override public void validate( MetadataExportParams params ) { } @Override @SuppressWarnings( "unchecked" ) public MetadataExportParams getParamsFromMap( Map<String, List<String>> parameters ) { MetadataExportParams params = new MetadataExportParams(); Map<Class<? extends IdentifiableObject>, Map<String, List<String>>> map = new HashMap<>(); if ( parameters.containsKey( "fields" ) ) { params.setDefaultFields( parameters.get( "fields" ) ); parameters.remove( "fields" ); } if ( parameters.containsKey( "filter" ) ) { params.setDefaultFilter( parameters.get( "filter" ) ); parameters.remove( "filter" ); } if ( parameters.containsKey( "order" ) ) { params.setDefaultOrder( parameters.get( "order" ) ); parameters.remove( "order" ); } for ( String parameterKey : parameters.keySet() ) { String[] parameter = parameterKey.split( ":" ); Schema schema = schemaService.getSchemaByPluralName( parameter[0] ); if ( schema == null || !schema.isIdentifiableObject() ) { continue; } Class<? extends IdentifiableObject> klass = (Class<? extends IdentifiableObject>) schema.getKlass(); // class is enabled if value = true, or fields/filter/order is present if ( "true".equalsIgnoreCase( parameters.get( parameterKey ).get( 0 ) ) || (parameter.length > 1 && ("fields".equalsIgnoreCase( parameter[1] ) || "filter".equalsIgnoreCase( parameter[1] ) || "order".equalsIgnoreCase( parameter[1] ))) ) { if ( !map.containsKey( klass ) ) map.put( klass, new HashMap<>() ); } else { continue; } if ( parameter.length > 1 ) { if ( "fields".equalsIgnoreCase( parameter[1] ) ) { if ( !map.get( klass ).containsKey( "fields" ) ) map.get( klass ).put( "fields", new ArrayList<>() ); map.get( klass ).get( "fields" ).addAll( parameters.get( parameterKey ) ); } if ( "filter".equalsIgnoreCase( parameter[1] ) ) { if ( !map.get( klass ).containsKey( "filter" ) ) map.get( klass ).put( "filter", new ArrayList<>() ); map.get( klass ).get( "filter" ).addAll( parameters.get( parameterKey ) ); } if ( "order".equalsIgnoreCase( parameter[1] ) ) { if ( !map.get( klass ).containsKey( "order" ) ) map.get( klass ).put( "order", new ArrayList<>() ); map.get( klass ).get( "order" ).addAll( parameters.get( parameterKey ) ); } } } map.keySet().forEach( params::addClass ); for ( Class<? extends IdentifiableObject> klass : map.keySet() ) { Map<String, List<String>> classMap = map.get( klass ); Schema schema = schemaService.getDynamicSchema( klass ); if ( classMap.containsKey( "fields" ) ) params.addFields( klass, classMap.get( "fields" ) ); if ( classMap.containsKey( "filter" ) && classMap.containsKey( "order" ) ) { OrderParams orderParams = new OrderParams( Sets.newHashSet( classMap.get( "order" ) ) ); Query query = queryService.getQueryFromUrl( klass, classMap.get( "filter" ), orderParams.getOrders( schema ) ); query.setDefaultOrder(); params.addQuery( query ); } else if ( classMap.containsKey( "filter" ) ) { Query query = queryService.getQueryFromUrl( klass, classMap.get( "filter" ), new ArrayList<>() ); query.setDefaultOrder(); params.addQuery( query ); } else if ( classMap.containsKey( "order" ) ) { OrderParams orderParams = new OrderParams(); orderParams.setOrder( Sets.newHashSet( classMap.get( "order" ) ) ); Query query = queryService.getQueryFromUrl( klass, new ArrayList<>(), orderParams.getOrders( schema ) ); query.setDefaultOrder(); params.addQuery( query ); } } return params; } @Override public SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> getMetadataWithDependencies( IdentifiableObject object ) { SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata = new SetMap<>(); if ( DataSet.class.isInstance( object ) ) return handleDataSet( metadata, (DataSet) object ); if ( Program.class.isInstance( object ) ) return handleProgram( metadata, (Program) object ); return metadata; } @Override public RootNode getMetadataWithDependenciesAsNode( IdentifiableObject object ) { RootNode rootNode = NodeUtils.createMetadata(); rootNode.addChild( new SimpleNode( "date", new Date(), true ) ); SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata = getMetadataWithDependencies( object ); for ( Class<? extends IdentifiableObject> klass : metadata.keySet() ) { rootNode.addChild( fieldFilterService.filter( klass, Lists.newArrayList( metadata.get( klass ) ), Lists.newArrayList( ":owner" ) ) ); } return rootNode; } // Utility Methods private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleDataSet( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataSet dataSet ) { metadata.putValue( DataSet.class, dataSet ); dataSet.getDataSetElements().forEach( dataSetElement -> handleDataSetElement( metadata, dataSetElement ) ); dataSet.getSections().forEach( section -> handleSection( metadata, section ) ); dataSet.getIndicators().forEach( indicator -> handleIndicator( metadata, indicator ) ); handleDataEntryForm( metadata, dataSet.getDataEntryForm() ); handleLegendSet( metadata, dataSet.getLegendSet() ); handleCategoryCombo( metadata, dataSet.getCategoryCombo() ); dataSet.getCompulsoryDataElementOperands().forEach( dataElementOperand -> handleDataElementOperand( metadata, dataElementOperand ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleDataElementOperand( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElementOperand dataElementOperand ) { if ( dataElementOperand == null ) return metadata; handleCategoryOptionCombo( metadata, dataElementOperand.getCategoryOptionCombo() ); handleLegendSet( metadata, dataElementOperand.getLegendSet() ); handleDataElement( metadata, dataElementOperand.getDataElement() ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleCategoryOptionCombo( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElementCategoryOptionCombo categoryOptionCombo ) { if ( categoryOptionCombo == null ) return metadata; metadata.putValue( DataElementCategoryOptionCombo.class, categoryOptionCombo ); handleCategoryCombo( metadata, categoryOptionCombo.getCategoryCombo() ); categoryOptionCombo.getCategoryOptions().forEach( categoryOption -> handleCategoryOption( metadata, categoryOption ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleCategoryCombo( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElementCategoryCombo categoryCombo ) { if ( categoryCombo == null ) return metadata; metadata.putValue( DataElementCategoryCombo.class, categoryCombo ); categoryCombo.getCategories().forEach( category -> handleCategory( metadata, category ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleCategory( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElementCategory category ) { if ( category == null ) return metadata; metadata.putValue( DataElementCategory.class, category ); category.getCategoryOptions().forEach( categoryOption -> handleCategoryOption( metadata, categoryOption ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleCategoryOption( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElementCategoryOption categoryOption ) { if ( categoryOption == null ) return metadata; metadata.putValue( DataElementCategoryOption.class, categoryOption ); categoryOption.getCategoryOptionCombos().forEach( categoryOptionCombo -> handleCategoryOptionCombo( metadata, categoryOptionCombo ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleLegendSet( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, LegendSet legendSet ) { if ( legendSet == null ) return metadata; metadata.putValue( LegendSet.class, legendSet ); legendSet.getLegends().forEach( legend -> handleLegend( metadata, legend ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleLegend( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, Legend legend ) { if ( legend == null ) return metadata; metadata.putValue( Legend.class, legend ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleDataEntryForm( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataEntryForm dataEntryForm ) { if ( dataEntryForm == null ) return metadata; metadata.putValue( DataEntryForm.class, dataEntryForm ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleDataSetElement( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataSetElement dataSetElement ) { if ( dataSetElement == null ) return metadata; metadata.putValue( DataSetElement.class, dataSetElement ); handleDataElement( metadata, dataSetElement.getDataElement() ); handleCategoryCombo( metadata, dataSetElement.getCategoryCombo() ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleDataElement( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElement dataElement ) { if ( dataElement == null ) return metadata; metadata.putValue( DataElement.class, dataElement ); handleCategoryCombo( metadata, dataElement.getDataElementCategoryCombo() ); handleOptionSet( metadata, dataElement.getOptionSet() ); handleOptionSet( metadata, dataElement.getCommentOptionSet() ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleOptionSet( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, OptionSet optionSet ) { if ( optionSet == null ) return metadata; metadata.putValue( OptionSet.class, optionSet ); optionSet.getOptions().forEach( o -> handleOption( metadata, o ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleOption( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, Option option ) { if ( option == null ) return metadata; metadata.putValue( Option.class, option ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleSection( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, Section section ) { if ( section == null ) return metadata; metadata.putValue( Section.class, section ); section.getGreyedFields().forEach( dataElementOperand -> handleDataElementOperand( metadata, dataElementOperand ) ); section.getIndicators().forEach( indicator -> handleIndicator( metadata, indicator ) ); section.getDataElements().forEach( dataElement -> handleDataElement( metadata, dataElement ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleIndicator( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, Indicator indicator ) { if ( indicator == null ) return metadata; metadata.putValue( Indicator.class, indicator ); handleIndicatorType( metadata, indicator.getIndicatorType() ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleIndicatorType( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, IndicatorType indicatorType ) { if ( indicatorType == null ) return metadata; metadata.putValue( IndicatorType.class, indicatorType ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgram( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, Program program ) { if ( program == null ) return metadata; metadata.putValue( Program.class, program ); handleCategoryCombo( metadata, program.getCategoryCombo() ); handleDataEntryForm( metadata, program.getDataEntryForm() ); handleTrackedEntity( metadata, program.getTrackedEntity() ); program.getProgramStages().forEach( programStage -> handleProgramStage( metadata, programStage ) ); program.getProgramAttributes().forEach( programTrackedEntityAttribute -> handleProgramTrackedEntityAttribute( metadata, programTrackedEntityAttribute ) ); program.getProgramIndicators().forEach( programIndicator -> handleProgramIndicator( metadata, programIndicator ) ); List<ProgramRule> programRules = programRuleService.getProgramRule( program ); List<ProgramRuleVariable> programRuleVariables = programRuleVariableService.getProgramRuleVariable( program ); programRules.forEach( programRule -> handleProgramRule( metadata, programRule ) ); programRuleVariables.forEach( programRuleVariable -> handleProgramRuleVariable( metadata, programRuleVariable ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramRuleVariable( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramRuleVariable programRuleVariable ) { if ( programRuleVariable == null ) return metadata; metadata.putValue( ProgramRuleVariable.class, programRuleVariable ); handleTrackedEntityAttribute( metadata, programRuleVariable.getAttribute() ); handleDataElement( metadata, programRuleVariable.getDataElement() ); handleProgramStage( metadata, programRuleVariable.getProgramStage() ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleTrackedEntityAttribute( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, TrackedEntityAttribute trackedEntityAttribute ) { if ( trackedEntityAttribute == null ) return metadata; metadata.putValue( TrackedEntityAttribute.class, trackedEntityAttribute ); handleOptionSet( metadata, trackedEntityAttribute.getOptionSet() ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramRule( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramRule programRule ) { if ( programRule == null ) return metadata; metadata.putValue( ProgramRule.class, programRule ); programRule.getProgramRuleActions().forEach( programRuleAction -> handleProgramRuleAction( metadata, programRuleAction ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramRuleAction( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramRuleAction programRuleAction ) { if ( programRuleAction == null ) return metadata; metadata.putValue( ProgramRuleAction.class, programRuleAction ); handleDataElement( metadata, programRuleAction.getDataElement() ); handleTrackedEntityAttribute( metadata, programRuleAction.getAttribute() ); handleProgramIndicator( metadata, programRuleAction.getProgramIndicator() ); handleProgramStageSection( metadata, programRuleAction.getProgramStageSection() ); handleProgramStage( metadata, programRuleAction.getProgramStage() ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramTrackedEntityAttribute( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramTrackedEntityAttribute programTrackedEntityAttribute ) { if ( programTrackedEntityAttribute == null ) return metadata; metadata.putValue( ProgramTrackedEntityAttribute.class, programTrackedEntityAttribute ); handleTrackedEntityAttribute( metadata, programTrackedEntityAttribute.getAttribute() ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramStage( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramStage programStage ) { if ( programStage == null ) return metadata; metadata.putValue( ProgramStage.class, programStage ); programStage.getProgramStageDataElements().forEach( programStageDataElement -> handleProgramStageDataElement( metadata, programStageDataElement ) ); programStage.getProgramStageSections().forEach( programStageSection -> handleProgramStageSection( metadata, programStageSection ) ); handleDataEntryForm( metadata, programStage.getDataEntryForm() ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramStageSection( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramStageSection programStageSection ) { if ( programStageSection == null ) return metadata; metadata.putValue( ProgramStageSection.class, programStageSection ); programStageSection.getProgramStageDataElements().forEach( programStageDataElement -> handleProgramStageDataElement( metadata, programStageDataElement ) ); programStageSection.getProgramIndicators().forEach( programIndicator -> handleProgramIndicator( metadata, programIndicator ) ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramIndicator( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramIndicator programIndicator ) { if ( programIndicator == null ) return metadata; metadata.putValue( ProgramIndicator.class, programIndicator ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramStageDataElement( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramStageDataElement programStageDataElement ) { if ( programStageDataElement == null ) return metadata; metadata.putValue( ProgramStageDataElement.class, programStageDataElement ); handleDataElement( metadata, programStageDataElement.getDataElement() ); return metadata; } private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleTrackedEntity( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, TrackedEntity trackedEntity ) { if ( trackedEntity == null ) return metadata; metadata.putValue( TrackedEntity.class, trackedEntity ); return metadata; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1272"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package edu.wustl.catissuecore.action; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.actionForm.SimpleQueryInterfaceForm; import edu.wustl.catissuecore.dao.DAOFactory; import edu.wustl.catissuecore.dao.JDBCDAO; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.logger.Logger; /** * SimpleQueryInterfaceAction initializes the fields in the Simple Query Interface. * @author gautam_shetty */ public class SimpleQueryInterfaceAction extends SecureAction { /** * Overrides the execute method of Action class. */ public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SimpleQueryInterfaceForm simpleQueryInterfaceForm = (SimpleQueryInterfaceForm) form; int counter = Integer.parseInt(simpleQueryInterfaceForm.getCounter()); for (int i=1;i<=counter;i++) { //Key of previous object. String prevKey = "SimpleConditionsNode:"+(i-1)+"_Condition_DataElement_table"; String prevValue = (String)simpleQueryInterfaceForm.getValue(prevKey); //Key of present object. String key = "SimpleConditionsNode:"+i+"_Condition_DataElement_table"; String value = (String)simpleQueryInterfaceForm.getValue(key); //Key of the next operator (AND/OR). String nextOperatorKey = "SimpleConditionsNode:"+i+"_Operator_operator"; String nextOperatorValue = (String)simpleQueryInterfaceForm.getValue(nextOperatorKey); if (value != null) { if (!value.equals(Constants.SELECT_OPTION)) { setColumnNames(request, i, value); } } String sql = " select TABLE_A.ALIAS_NAME, TABLE_A.DISPLAY_NAME " + " from catissue_table_relation TABLE_R, " + " CATISSUE_QUERY_INTERFACE_TABLE_DATA TABLE_A, " + " CATISSUE_QUERY_INTERFACE_TABLE_DATA TABLE_B " + " where TABLE_R.PARENT_TABLE_ID = TABLE_A.TABLE_ID and " + " TABLE_R.CHILD_TABLE_ID = TABLE_B.TABLE_ID "; Logger.out.debug("Check sql....................."+sql); JDBCDAO jdbcDao = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO); jdbcDao.openSession(null); List checkList = jdbcDao.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null); jdbcDao.closeSession(); if (i == counter) { if (prevValue != null) setNextTableNames(request, i, prevValue, checkList); else setAllTableNames(request); } else { if (nextOperatorValue != null && !"".equals(nextOperatorValue)) { String prevValueDisplayName = null; String objectNameValueBeanList = "objectList"+i; JDBCDAO jdbcDAO = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO); jdbcDAO.openSession(null); sql = "select DISPLAY_NAME from CATISSUE_QUERY_INTERFACE_TABLE_DATA where ALIAS_NAME='"+value+"'"; List list = jdbcDAO.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null); jdbcDAO.closeSession(); if (!list.isEmpty()) { List rowList = (List)list.get(0); prevValueDisplayName = (String)rowList.get(0); } NameValueBean nameValueBean = new NameValueBean(); nameValueBean.setName(prevValueDisplayName); nameValueBean.setValue(value); List objectList = new ArrayList(); objectList.add(nameValueBean); request.setAttribute(objectNameValueBeanList, objectList); } } } request.setAttribute(Constants.ATTRIBUTE_NAME_LIST, Constants.ATTRIBUTE_NAME_ARRAY); request.setAttribute(Constants.ATTRIBUTE_CONDITION_LIST, Constants.ATTRIBUTE_CONDITION_ARRAY); HttpSession session =request.getSession(); session.setAttribute(Constants.SIMPLE_QUERY_ALIAS_NAME,null); session.setAttribute(Constants.SIMPLE_QUERY_COUNTER,null); session.setAttribute(Constants.SIMPLE_QUERY_MAP,null); String pageOf = request.getParameter(Constants.PAGEOF); request.setAttribute(Constants.PAGEOF, pageOf); String target = Constants.PAGEOF_EDIT_OBJECT; if (Constants.PAGEOF_SIMPLE_QUERY_INTERFACE.equals(pageOf)) target = Constants.PAGEOF_SIMPLE_QUERY_INTERFACE; if(pageOf != null && pageOf.equals("pageOfSimpleQueryInterface" ) ) request.setAttribute("menuSelected",new String("17") ); return mapping.findForward(target); } /** * Sets column names depending on the table name selected for that condition. * @param request HttpServletRequest * @param i number of row. * @param value table name. * @throws DAOException * @throws ClassNotFoundException */ private void setColumnNames(HttpServletRequest request, int i, String value) throws DAOException, ClassNotFoundException { String attributeNameList = "attributeNameList"+i; String attributeDisplayNameList = "attributeDisplayNameList"+i; String sql = " SELECT tableData2.ALIAS_NAME, temp.COLUMN_NAME, temp.ATTRIBUTE_TYPE, temp.TABLES_IN_PATH, temp.DISPLAY_NAME " + " from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData2 join " + " ( SELECT columnData.COLUMN_NAME, columnData.TABLE_ID, columnData.ATTRIBUTE_TYPE, " + " displayData.DISPLAY_NAME, relationData.TABLES_IN_PATH " + " FROM CATISSUE_QUERY_INTERFACE_COLUMN_DATA columnData, " + " CATISSUE_TABLE_RELATION relationData, " + " CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData, " + " CATISSUE_SEARCH_DISPLAY_DATA displayData " + " where relationData.CHILD_TABLE_ID = columnData.TABLE_ID and " + " relationData.PARENT_TABLE_ID = tableData.TABLE_ID and " + " relationData.RELATIONSHIP_ID = displayData.RELATIONSHIP_ID and " + " columnData.IDENTIFIER = displayData.COL_ID and " + " tableData.ALIAS_NAME = '"+value+"') as temp " + " on temp.TABLE_ID = tableData2.TABLE_ID "; Logger.out.debug("SQL*****************************"+sql); JDBCDAO jdbcDao = new JDBCDAO(); jdbcDao.openSession(null); List list = jdbcDao.executeQuery(sql, null, Constants.INSECURE_RETRIEVE, null,null); jdbcDao.closeSession(); String [] columnNameList = new String[list.size()]; String [] columnDisplayNameList = new String[list.size()]; Iterator iterator = list.iterator(); int j = 0, k=0; while (iterator.hasNext()) { List rowList = (List)iterator.next(); columnNameList[k] = (String)rowList.get(j++)+"."+(String)rowList.get(j++) +"."+(String)rowList.get(j++); String tablesInPath = (String)rowList.get(j++); if ((tablesInPath != null) && ("".equals(tablesInPath) == false)) { columnNameList[k] = columnNameList[k]+"."+tablesInPath; } columnDisplayNameList[k] = (String)rowList.get(j++); j = 0; k++; } request.setAttribute(attributeNameList, columnNameList); request.setAttribute(attributeDisplayNameList, columnDisplayNameList); } /** * Sets the next table names depending on the table in the previous row. * @param request * @param i * @param prevValue previous table name. * @param nextOperatorValue * @param checkList * @throws DAOException * @throws ClassNotFoundException */ private void setNextTableNames(HttpServletRequest request, int i, String prevValue, List checkList) throws DAOException, ClassNotFoundException { String objectNameList = "objectList"+i; List objectList = new ArrayList(); String sql =" (select temp.ALIAS_NAME, temp.DISPLAY_NAME " + " from " + " (select relationData.FIRST_TABLE_ID, tableData.ALIAS_NAME, tableData.DISPLAY_NAME " + " from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData join " + " CATISSUE_RELATED_TABLES_MAP relationData " + " on tableData.TABLE_ID = relationData.SECOND_TABLE_ID) as temp join CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData2 " + " on temp.FIRST_TABLE_ID = tableData2.TABLE_ID " + " where tableData2.ALIAS_NAME = '"+prevValue+"') " + " union " + " (select temp1.ALIAS_NAME, temp1.DISPLAY_NAME " + " from " + " (select relationData1.SECOND_TABLE_ID, tableData4.ALIAS_NAME, tableData4.DISPLAY_NAME " + " from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData4 join " + " CATISSUE_RELATED_TABLES_MAP relationData1 " + " on tableData4.TABLE_ID = relationData1.FIRST_TABLE_ID) as temp1 join CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData3 " + " on temp1.SECOND_TABLE_ID = tableData3.TABLE_ID " + " where tableData3.ALIAS_NAME = '"+prevValue+"')"; Logger.out.debug("TABLE SQL*****************************"+sql); JDBCDAO jdbcDao = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO); jdbcDao.openSession(null); List list = jdbcDao.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null); jdbcDao.closeSession(); //Adding NameValueBean of select option. NameValueBean nameValueBean = new NameValueBean(); nameValueBean.setName(Constants.SELECT_OPTION); nameValueBean.setValue("-1"); objectList.add(nameValueBean); //Adding the NameValueBean of previous selected object. JDBCDAO jdbcDAO = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO); jdbcDAO.openSession(null); sql = "select DISPLAY_NAME from CATISSUE_QUERY_INTERFACE_TABLE_DATA where ALIAS_NAME='"+prevValue+"'"; List prevValueDisplayNameList = jdbcDAO.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null); jdbcDAO.closeSession(); if (!prevValueDisplayNameList.isEmpty()) { List rowList = (List)prevValueDisplayNameList.get(0); nameValueBean = new NameValueBean(); nameValueBean.setName((String)rowList.get(0)); nameValueBean.setValue(prevValue); objectList.add(nameValueBean); } Iterator iterator = list.iterator(); while (iterator.hasNext()) { int j=0; List rowList = (List)iterator.next(); if (checkForTable(rowList, checkList)) { nameValueBean = new NameValueBean(); nameValueBean.setValue((String)rowList.get(j++)); nameValueBean.setName((String)rowList.get(j)); objectList.add(nameValueBean); } } request.setAttribute(objectNameList, objectList); } /** * Returns the object id of the protection element that represents * the Action that is being requested for invocation. * @param clazz * @return */ protected String getObjectIdForSecureMethodAccess(HttpServletRequest request) { String aliasName = request.getParameter("aliasName"); if(aliasName!=null && !aliasName.equals("")) { return this.getClass().getName()+"_"+aliasName; } else { return super.getObjectIdForSecureMethodAccess(request); } } /** * @param mapping * @return */ protected ActionForward getActionForward(HttpServletRequest request,ActionMapping mapping) { String aliasName = request.getParameter("aliasName"); if(aliasName.equals("User") || aliasName.equals("Institution") || aliasName.equals("Department")|| aliasName.equals("CancerResearchGroup")|| aliasName.equals("Site")|| aliasName.equals("StorageType")|| aliasName.equals("StorageContainer")|| aliasName.equals("BioHazard")|| aliasName.equals("CollectionProtocol")|| aliasName.equals("DistributionProtocol")) { return mapping.findForward(Constants.ACCESS_DENIED_ADMIN); } else if(aliasName.equals("Participant") ||aliasName.equals("CollectionProtocolRegistration") ||aliasName.equals("SpecimenCollectionGroup") ||aliasName.equals("Specimen") ||aliasName.equals("Distribution")) { return mapping.findForward(Constants.ACCESS_DENIED_BIOSPECIMEN); } else { return mapping.findForward(Constants.ACCESS_DENIED); } } private boolean checkForTable(List rowList, List checkList) { String aliasName = (String)rowList.get(0), displayName = (String)rowList.get(1); Iterator iterator = checkList.iterator(); while (iterator.hasNext()) { List row = (List) iterator.next(); if (aliasName.equals((String) row.get(0)) && displayName.equals((String) row.get(1))) { return true; } } return false; } /** * Sets all the tables in the simple query interface. * @param request * @throws DAOException * @throws ClassNotFoundException */ private void setAllTableNames(HttpServletRequest request)throws DAOException, ClassNotFoundException { String sql = " select distinct tableData.DISPLAY_NAME, tableData.ALIAS_NAME " + " from CATISSUE_TABLE_RELATION tableRelation join CATISSUE_QUERY_INTERFACE_TABLE_DATA " + " tableData on tableRelation.PARENT_TABLE_ID = tableData.TABLE_ID "; String aliasName = request.getParameter(Constants.TABLE_ALIAS_NAME); if ((aliasName != null) && (!"".equals(aliasName))) { sql = sql + " where tableData.ALIAS_NAME = '"+ aliasName +"'"; request.setAttribute(Constants.TABLE_ALIAS_NAME,aliasName); } sql = sql + " ORDER BY tableData.DISPLAY_NAME "; JDBCDAO jdbcDAO = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO); jdbcDAO.openSession(null); List tableList = jdbcDAO.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null); jdbcDAO.closeSession(); String [] objectDisplayNames = null; String [] objectAliasNames = null; int i = 0; if ((aliasName != null) && (!"".equals(aliasName))) { objectDisplayNames = new String[tableList.size()]; objectAliasNames = new String[tableList.size()]; setColumnNames(request,1,aliasName); } else { objectDisplayNames = new String[tableList.size()+1]; objectAliasNames = new String[tableList.size()+1]; objectAliasNames[i] = "-1"; objectDisplayNames[i] = Constants.SELECT_OPTION; i++; } Iterator objIterator = tableList.iterator(); while (objIterator.hasNext()) { List row = (List) objIterator.next(); objectDisplayNames[i] = (String)row.get(0); objectAliasNames[i] = (String)row.get(1); i++; } request.setAttribute(Constants.OBJECT_DISPLAY_NAME_LIST, objectDisplayNames); request.setAttribute(Constants.OBJECT_ALIAS_NAME_LIST, objectAliasNames); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1273"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.jfree.text; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.text.AttributedString; import java.text.BreakIterator; import org.jfree.base.BaseBoot; import org.jfree.ui.TextAnchor; import org.jfree.util.Log; import org.jfree.util.LogContext; import org.jfree.util.ObjectUtilities; /** * Some utility methods for working with text in Java2D. */ public class TextUtilities { /** Access to logging facilities. */ protected static final LogContext logger = Log.createContext( TextUtilities.class); /** * A flag that controls whether or not the rotated string workaround is * used. */ private static boolean useDrawRotatedStringWorkaround; /** * A flag that controls whether the FontMetrics.getStringBounds() method * is used or a workaround is applied. */ private static boolean useFontMetricsGetStringBounds; static { try { boolean isJava14 = ObjectUtilities.isJDK14(); String configRotatedStringWorkaround = BaseBoot.getInstance() .getGlobalConfig().getConfigProperty( "org.jfree.text.UseDrawRotatedStringWorkaround", "auto"); if (configRotatedStringWorkaround.equals("auto")) { useDrawRotatedStringWorkaround = !isJava14; } else { useDrawRotatedStringWorkaround = configRotatedStringWorkaround.equals("true"); } String configFontMetricsStringBounds = BaseBoot.getInstance() .getGlobalConfig().getConfigProperty( "org.jfree.text.UseFontMetricsGetStringBounds", "auto"); if (configFontMetricsStringBounds.equals("auto")) { useFontMetricsGetStringBounds = isJava14; } else { useFontMetricsGetStringBounds = configFontMetricsStringBounds.equals("true"); } } catch (Exception e) { // ignore everything. useDrawRotatedStringWorkaround = true; useFontMetricsGetStringBounds = true; } } /** * Private constructor prevents object creation. */ private TextUtilities() { // prevent instantiation } /** * Creates a {@link TextBlock} from a <code>String</code>. Line breaks * are added where the <code>String</code> contains '\n' characters. * * @param text the text. * @param font the font. * @param paint the paint. * * @return A text block. */ public static TextBlock createTextBlock(String text, Font font, Paint paint) { if (text == null) { throw new IllegalArgumentException("Null 'text' argument."); } TextBlock result = new TextBlock(); String input = text; boolean moreInputToProcess = (text.length() > 0); int start = 0; while (moreInputToProcess) { int index = input.indexOf("\n"); if (index > start) { String line = input.substring(start, index); if (index < input.length() - 1) { result.addLine(line, font, paint); input = input.substring(index + 1); } else { moreInputToProcess = false; } } else if (index == start) { if (index < input.length() - 1) { input = input.substring(index + 1); } else { moreInputToProcess = false; } } else { result.addLine(input, font, paint); moreInputToProcess = false; } } return result; } /** * Creates a new text block from the given string, breaking the * text into lines so that the <code>maxWidth</code> value is * respected. * * @param text the text. * @param font the font. * @param paint the paint. * @param maxWidth the maximum width for each line. * @param measurer the text measurer. * * @return A text block. */ public static TextBlock createTextBlock(String text, Font font, Paint paint, float maxWidth, TextMeasurer measurer) { return createTextBlock(text, font, paint, maxWidth, Integer.MAX_VALUE, measurer); } /** * Creates a new text block from the given string, breaking the * text into lines so that the <code>maxWidth</code> value is * respected. * * @param text the text. * @param font the font. * @param paint the paint. * @param maxWidth the maximum width for each line. * @param maxLines the maximum number of lines. * @param measurer the text measurer. * * @return A text block. */ public static TextBlock createTextBlock(String text, Font font, Paint paint, float maxWidth, int maxLines, TextMeasurer measurer) { TextBlock result = new TextBlock(); BreakIterator iterator = BreakIterator.getLineInstance(); iterator.setText(text); int current = 0; int lines = 0; int length = text.length(); while (current < length && lines < maxLines) { int next = nextLineBreak(text, current, maxWidth, iterator, measurer); if (next == BreakIterator.DONE) { result.addLine(text.substring(current), font, paint); return result; } result.addLine(text.substring(current, next), font, paint); lines++; current = next; while (current < text.length()&& text.charAt(current) == '\n') { current++; } } if (current < length) { TextLine lastLine = result.getLastLine(); TextFragment lastFragment = lastLine.getLastTextFragment(); String oldStr = lastFragment.getText(); String newStr = "..."; if (oldStr.length() > 3) { newStr = oldStr.substring(0, oldStr.length() - 3) + "..."; } lastLine.removeFragment(lastFragment); TextFragment newFragment = new TextFragment(newStr, lastFragment.getFont(), lastFragment.getPaint()); lastLine.addFragment(newFragment); } return result; } /** * Returns the character index of the next line break. * * @param text the text (<code>null</code> not permitted). * @param start the start index. * @param width the target display width. * @param iterator the word break iterator. * @param measurer the text measurer. * * @return The index of the next line break. */ private static int nextLineBreak(String text, int start, float width, BreakIterator iterator, TextMeasurer measurer) { // this method is (loosely) based on code in JFreeReport's // TextParagraph class int current = start; int end; float x = 0.0f; boolean firstWord = true; int newline = text.indexOf('\n', start); if (newline < 0) { newline = Integer.MAX_VALUE; } while (((end = iterator.following(current)) != BreakIterator.DONE)) { x += measurer.getStringWidth(text, current, end); if (x > width) { if (firstWord) { while (measurer.getStringWidth(text, start, end) > width) { end if (end <= start) { return end; } } return end; } else { end = iterator.previous(); return end; } } else { if (end > newline) { return newline; } } // we found at least one word that fits ... firstWord = false; current = end; } return BreakIterator.DONE; } /** * Returns the bounds for the specified text. * * @param text the text (<code>null</code> permitted). * @param g2 the graphics context (not <code>null</code>). * @param fm the font metrics (not <code>null</code>). * * @return The text bounds (<code>null</code> if the <code>text</code> * argument is <code>null</code>). */ public static Rectangle2D getTextBounds(String text, Graphics2D g2, FontMetrics fm) { Rectangle2D bounds; if (TextUtilities.useFontMetricsGetStringBounds) { bounds = fm.getStringBounds(text, g2); // getStringBounds() can return incorrect height for some Unicode // characters...see bug parade 6183356, let's replace it with // something correct LineMetrics lm = fm.getFont().getLineMetrics(text, g2.getFontRenderContext()); bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(), lm.getHeight()); } else { double width = fm.stringWidth(text); double height = fm.getHeight(); if (logger.isDebugEnabled()) { logger.debug("Height = " + height); } bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width, height); } return bounds; } /** * Draws a string such that the specified anchor point is aligned to the * given (x, y) location. * * @param text the text. * @param g2 the graphics device. * @param x the x coordinate (Java 2D). * @param y the y coordinate (Java 2D). * @param anchor the anchor location. * * @return The text bounds (adjusted for the text position). */ public static Rectangle2D drawAlignedString(String text, Graphics2D g2, float x, float y, TextAnchor anchor) { Rectangle2D textBounds = new Rectangle2D.Double(); float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor, textBounds); // adjust text bounds to match string position textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2], textBounds.getWidth(), textBounds.getHeight()); g2.drawString(text, x + adjust[0], y + adjust[1]); return textBounds; } /** * A utility method that calculates the anchor offsets for a string. * Normally, the (x, y) coordinate for drawing text is a point on the * baseline at the left of the text string. If you add these offsets to * (x, y) and draw the string, then the anchor point should coincide with * the (x, y) point. * * @param g2 the graphics device (not <code>null</code>). * @param text the text. * @param anchor the anchor point. * @param textBounds the text bounds (if not <code>null</code>, this * object will be updated by this method to match the * string bounds). * * @return The offsets. */ private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2, String text, TextAnchor anchor, Rectangle2D textBounds) { float[] result = new float[3]; FontRenderContext frc = g2.getFontRenderContext(); Font f = g2.getFont(); FontMetrics fm = g2.getFontMetrics(f); Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm); LineMetrics metrics = f.getLineMetrics(text, frc); float ascent = metrics.getAscent(); result[2] = -ascent; float halfAscent = ascent / 2.0f; float descent = metrics.getDescent(); float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor.isHorizontalCenter()) { xAdj = (float) -bounds.getWidth() / 2.0f; } else if (anchor.isRight()) { xAdj = (float) -bounds.getWidth(); } if (anchor.isTop()) { yAdj = -descent - leading + (float) bounds.getHeight(); } else if (anchor.isHalfAscent()) { yAdj = halfAscent; } else if (anchor.isVerticalCenter()) { yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0); } else if (anchor.isBaseline()) { yAdj = 0.0f; } else if (anchor.isBottom()) { yAdj = -metrics.getDescent() - metrics.getLeading(); } if (textBounds != null) { textBounds.setRect(bounds); } result[0] = xAdj; result[1] = yAdj; return result; } /** * A utility method for drawing rotated text. * <P> * A common rotation is -Math.PI/2 which draws text 'vertically' (with the * top of the characters on the left). * * @param text the text. * @param g2 the graphics device. * @param angle the angle of the (clockwise) rotation (in radians). * @param x the x-coordinate. * @param y the y-coordinate. */ public static void drawRotatedString(String text, Graphics2D g2, double angle, float x, float y) { drawRotatedString(text, g2, x, y, angle, x, y); } /** * A utility method for drawing rotated text. * <P> * A common rotation is -Math.PI/2 which draws text 'vertically' (with the * top of the characters on the left). * * @param text the text. * @param g2 the graphics device. * @param textX the x-coordinate for the text (before rotation). * @param textY the y-coordinate for the text (before rotation). * @param angle the angle of the (clockwise) rotation (in radians). * @param rotateX the point about which the text is rotated. * @param rotateY the point about which the text is rotated. */ public static void drawRotatedString(String text, Graphics2D g2, float textX, float textY, double angle, float rotateX, float rotateY) { if ((text == null) || (text.equals(""))) { return; } if (angle == 0.0) { drawAlignedString(text, g2, textY, textY, TextAnchor.BASELINE_LEFT); return; } AffineTransform saved = g2.getTransform(); AffineTransform rotate = AffineTransform.getRotateInstance( angle, rotateX, rotateY); g2.transform(rotate); if (useDrawRotatedStringWorkaround) { // workaround for JDC bug ID 4312117 and others... TextLayout tl = new TextLayout(text, g2.getFont(), g2.getFontRenderContext()); tl.draw(g2, textX, textY); } else { AttributedString as = new AttributedString(text, g2.getFont().getAttributes()); g2.drawString(as.getIterator(), textX, textY); } g2.setTransform(saved); } /** * Draws a string that is aligned by one anchor point and rotated about * another anchor point. * * @param text the text. * @param g2 the graphics device. * @param x the x-coordinate for positioning the text. * @param y the y-coordinate for positioning the text. * @param textAnchor the text anchor. * @param angle the rotation angle. * @param rotationX the x-coordinate for the rotation anchor point. * @param rotationY the y-coordinate for the rotation anchor point. */ public static void drawRotatedString(String text, Graphics2D g2, float x, float y, TextAnchor textAnchor, double angle, float rotationX, float rotationY) { if (text == null || text.equals("")) { return; } if (angle == 0.0) { drawAlignedString(text, g2, x, y, textAnchor); } else { float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle, rotationX, rotationY); } } /** * Draws a string that is aligned by one anchor point and rotated about * another anchor point. * * @param text the text. * @param g2 the graphics device. * @param x the x-coordinate for positioning the text. * @param y the y-coordinate for positioning the text. * @param textAnchor the text anchor. * @param angle the rotation angle (in radians). * @param rotationAnchor the rotation anchor. */ public static void drawRotatedString(String text, Graphics2D g2, float x, float y, TextAnchor textAnchor, double angle, TextAnchor rotationAnchor) { if (text == null || text.equals("")) { return; } if (angle == 0.0) { drawAlignedString(text, g2, x, y, textAnchor); } else { float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); float[] rotateAdj = deriveRotationAnchorOffsets(g2, text, rotationAnchor); drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle, x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]); } } /** * Returns a shape that represents the bounds of the string after the * specified rotation has been applied. * * @param text the text (<code>null</code> permitted). * @param g2 the graphics device. * @param x the x coordinate for the anchor point. * @param y the y coordinate for the anchor point. * @param textAnchor the text anchor. * @param angle the angle. * @param rotationAnchor the rotation anchor. * * @return The bounds (possibly <code>null</code>). */ public static Shape calculateRotatedStringBounds(String text, Graphics2D g2, float x, float y, TextAnchor textAnchor, double angle, TextAnchor rotationAnchor) { if (text == null || text.equals("")) { return null; } float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); if (logger.isDebugEnabled()) { logger.debug("TextBoundsAnchorOffsets = " + textAdj[0] + ", " + textAdj[1]); } float[] rotateAdj = deriveRotationAnchorOffsets(g2, text, rotationAnchor); if (logger.isDebugEnabled()) { logger.debug("RotationAnchorOffsets = " + rotateAdj[0] + ", " + rotateAdj[1]); } Shape result = calculateRotatedStringBounds(text, g2, x + textAdj[0], y + textAdj[1], angle, x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]); return result; } /** * A utility method that calculates the anchor offsets for a string. * Normally, the (x, y) coordinate for drawing text is a point on the * baseline at the left of the text string. If you add these offsets to * (x, y) and draw the string, then the anchor point should coincide with * the (x, y) point. * * @param g2 the graphics device (not <code>null</code>). * @param text the text. * @param anchor the anchor point. * * @return The offsets. */ private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2, String text, TextAnchor anchor) { float[] result = new float[2]; FontRenderContext frc = g2.getFontRenderContext(); Font f = g2.getFont(); FontMetrics fm = g2.getFontMetrics(f); Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm); LineMetrics metrics = f.getLineMetrics(text, frc); float ascent = metrics.getAscent(); float halfAscent = ascent / 2.0f; float descent = metrics.getDescent(); float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor.isHorizontalCenter()) { xAdj = (float) -bounds.getWidth() / 2.0f; } else if (anchor.isRight()) { xAdj = (float) -bounds.getWidth(); } if (anchor.isTop()) { yAdj = -descent - leading + (float) bounds.getHeight(); } else if (anchor.isHalfAscent()) { yAdj = halfAscent; } else if (anchor.isVerticalCenter()) { yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0); } else if (anchor.isBaseline()) { yAdj = 0.0f; } else if (anchor.isBottom()) { yAdj = -metrics.getDescent() - metrics.getLeading(); } result[0] = xAdj; result[1] = yAdj; return result; } /** * A utility method that calculates the rotation anchor offsets for a * string. These offsets are relative to the text starting coordinate * (<code>BASELINE_LEFT</code>). * * @param g2 the graphics device. * @param text the text. * @param anchor the anchor point. * * @return The offsets. */ private static float[] deriveRotationAnchorOffsets(Graphics2D g2, String text, TextAnchor anchor) { float[] result = new float[2]; FontRenderContext frc = g2.getFontRenderContext(); LineMetrics metrics = g2.getFont().getLineMetrics(text, frc); FontMetrics fm = g2.getFontMetrics(); Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm); float ascent = metrics.getAscent(); float halfAscent = ascent / 2.0f; float descent = metrics.getDescent(); float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor.isLeft()) { xAdj = 0.0f; } else if (anchor.isHorizontalCenter()) { xAdj = (float) bounds.getWidth() / 2.0f; } else if (anchor.isRight()) { xAdj = (float) bounds.getWidth(); } if (anchor.isTop()) { yAdj = descent + leading - (float) bounds.getHeight(); } else if (anchor.isVerticalCenter()) { yAdj = descent + leading - (float) (bounds.getHeight() / 2.0); } else if (anchor.isHalfAscent()) { yAdj = -halfAscent; } else if (anchor.isBaseline()) { yAdj = 0.0f; } else if (anchor.isBottom()) { yAdj = metrics.getDescent() + metrics.getLeading(); } result[0] = xAdj; result[1] = yAdj; return result; } /** * Returns a shape that represents the bounds of the string after the * specified rotation has been applied. * * @param text the text (<code>null</code> permitted). * @param g2 the graphics device. * @param textX the x coordinate for the text. * @param textY the y coordinate for the text. * @param angle the angle. * @param rotateX the x coordinate for the rotation point. * @param rotateY the y coordinate for the rotation point. * * @return The bounds (<code>null</code> if <code>text</code> is * </code>null</code> or has zero length). */ public static Shape calculateRotatedStringBounds(String text, Graphics2D g2, float textX, float textY, double angle, float rotateX, float rotateY) { if ((text == null) || (text.equals(""))) { return null; } FontMetrics fm = g2.getFontMetrics(); Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm); AffineTransform translate = AffineTransform.getTranslateInstance( textX, textY); Shape translatedBounds = translate.createTransformedShape(bounds); AffineTransform rotate = AffineTransform.getRotateInstance( angle, rotateX, rotateY); Shape result = rotate.createTransformedShape(translatedBounds); return result; } /** * Returns the flag that controls whether the FontMetrics.getStringBounds() * method is used or not. If you are having trouble with label alignment * or positioning, try changing the value of this flag. * * @return A boolean. */ public static boolean getUseFontMetricsGetStringBounds() { return useFontMetricsGetStringBounds; } /** * Sets the flag that controls whether the FontMetrics.getStringBounds() * method is used or not. If you are having trouble with label alignment * or positioning, try changing the value of this flag. * * @param use the flag. */ public static void setUseFontMetricsGetStringBounds(boolean use) { useFontMetricsGetStringBounds = use; } /** * Returns the flag that controls whether or not a workaround is used for * drawing rotated strings. * * @return A boolean. */ public static boolean isUseDrawRotatedStringWorkaround() { return useDrawRotatedStringWorkaround; } /** * Sets the flag that controls whether or not a workaround is used for * drawing rotated strings. The related bug is on Sun's bug parade * (id 4312117) and the workaround involves using a <code>TextLayout</code> * instance to draw the text instead of calling the * <code>drawString()</code> method in the <code>Graphics2D</code> class. * * @param use the new flag value. */ public static void setUseDrawRotatedStringWorkaround(final boolean use) { useDrawRotatedStringWorkaround = use; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1274"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.eclipse.birt.report.engine.presentation; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.format.DateFormatter; import org.eclipse.birt.core.format.NumberFormatter; import org.eclipse.birt.core.format.StringFormatter; import org.eclipse.birt.core.template.TextTemplate; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.report.engine.api.CachedImage; import org.eclipse.birt.report.engine.api.EngineConstants; import org.eclipse.birt.report.engine.api.IHTMLImageHandler; import org.eclipse.birt.report.engine.api.IImage; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.content.ContentVisitorAdapter; import org.eclipse.birt.report.engine.content.ICellContent; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IDataContent; import org.eclipse.birt.report.engine.content.IForeignContent; import org.eclipse.birt.report.engine.content.IImageContent; import org.eclipse.birt.report.engine.content.ILabelContent; import org.eclipse.birt.report.engine.content.IListContent; import org.eclipse.birt.report.engine.content.IPageContent; import org.eclipse.birt.report.engine.content.IReportContent; import org.eclipse.birt.report.engine.content.IRowContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.content.ITableContent; import org.eclipse.birt.report.engine.content.ITextContent; import org.eclipse.birt.report.engine.css.engine.value.css.CSSValueConstants; import org.eclipse.birt.report.engine.executor.ExecutionContext; import org.eclipse.birt.report.engine.executor.template.TemplateExecutor; import org.eclipse.birt.report.engine.extension.IBaseResultSet; import org.eclipse.birt.report.engine.extension.IQueryResultSet; import org.eclipse.birt.report.engine.extension.IReportItemPresentation; import org.eclipse.birt.report.engine.extension.IRowSet; import org.eclipse.birt.report.engine.extension.internal.ExtensionManager; import org.eclipse.birt.report.engine.extension.internal.RowSet; import org.eclipse.birt.report.engine.extension.internal.SingleRowSet; import org.eclipse.birt.report.engine.ir.ExtendedItemDesign; import org.eclipse.birt.report.engine.ir.ListItemDesign; import org.eclipse.birt.report.engine.ir.ReportItemDesign; import org.eclipse.birt.report.engine.ir.TextItemDesign; import org.eclipse.birt.report.engine.script.internal.OnRenderScriptVisitor; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.ModuleUtil; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.w3c.dom.css.CSSValue; import com.ibm.icu.util.ULocale; public class LocalizedContentVisitor extends ContentVisitorAdapter { protected static Logger logger = Logger .getLogger( LocalizedContentVisitor.class.getName( ) ); private ExecutionContext context; private Locale locale; private String outputFormat; protected HashMap templates = new HashMap( ); private OnRenderScriptVisitor onRenderVisitor; public LocalizedContentVisitor( ExecutionContext context ) { this.context = context; this.locale = context.getLocale( ); this.outputFormat = context.getOutputFormat( ); this.onRenderVisitor = new OnRenderScriptVisitor( context ); } IReportContent getReportContent( ) { return context.getReportContent( ); } ReportDesignHandle getReportDesign( ) { return context.getDesign( ); } public IContent localize(IContent content) { Object value = content.accept( this, content ); return (IContent) value; } protected IContent localizeAllChildren( IContent content ) { ArrayList children = (ArrayList) content.getChildren( ); if ( children != null ) { for ( int i = 0; i < children.size( ); i++ ) { IContent child = (IContent) children.get( i ); IContent localChild = localize( child ); if ( localChild != child ) { // replace the child with the licallized child. children.set( i, localChild ); // set the locallized child's parent as orient child's // parent. localChild.setParent( content ); // copy all children of this child to its localized child, // also change all children's parent to this localized // child. Collection childrenOfLocalChild = localChild.getChildren( ); Iterator iter = child.getChildren( ).iterator( ); while ( iter.hasNext( ) ) { IContent childOfChild = (IContent) iter.next( ); if ( !childrenOfLocalChild.contains( childOfChild ) ) { childOfChild.setParent( localChild ); childrenOfLocalChild.add( childOfChild ); } } } localizeAllChildren( localChild ); } } return content; } public Object visitPage( IPageContent page, Object value ) { return page; } protected TextTemplate parseTemplate( String text ) { SoftReference templateRef = (SoftReference) templates.get( text ); TextTemplate template = null; if ( templateRef != null ) { template = (TextTemplate) templateRef.get( ); if ( template != null ) { return template; } } try { template = new org.eclipse.birt.core.template.TemplateParser( ) .parse( text ); templateRef = new SoftReference( template ); templates.put( text, templateRef ); } catch ( Exception ex ) { ex.printStackTrace( ); } return template; } String executeTemplate( TextTemplate template, HashMap values ) { return new TemplateExecutor( context ).execute( template, values ); } public Object visitList( IListContent list, Object value) { if ( list.getGenerateBy( ) instanceof ListItemDesign ) { handleOnRender( list ); } return list; } public Object visitTable( ITableContent table, Object value ) { handleOnRender( table ); String captionText = table.getCaption( ); String captionKey = table.getCaptionKey( ); captionText = localize( table, captionKey, captionText ); table.setCaption( captionText ); return table; } public Object visitRow( IRowContent row, Object value ) { handleOnRender( row ); return row; } public Object visitCell( ICellContent cell, Object value ) { handleOnRender( cell ); return cell; } /** * handle the data content. * * @param data * data content object */ public Object visitData( IDataContent data, Object value ) { handleOnRender( data ); processData( data ); return data; } /** * process the data content * * <li> localize the help text * <li> format the value * <li> handle it as it is an text. * * @param data * data object */ protected void processData( IDataContent data ) { String helpText = localize( data, data.getHelpKey( ), data.getHelpText( ) ); data.setHelpText( helpText ); String text = ""; //$NON-NLS-1$ if ( data.getLabelKey( ) != null || data.getLabelText( ) != null ) { text = localize( data, data.getLabelKey( ), data.getLabelText( ) ); } else { Object value = data.getValue( ); if ( value != null ) { IStyle style = data.getComputedStyle( ); if ( value instanceof Number ) { String format = style.getNumberFormat( ); NumberFormatter fmt = context.getNumberFormatter( format ); text = fmt.format( (Number) value ); CSSValue align = style .getProperty( IStyle.STYLE_NUMBER_ALIGN ); if ( align != null && align != CSSValueConstants.NONE_VALUE ) { data.getStyle( ).setProperty( IStyle.STYLE_TEXT_ALIGN, align ); } } else if ( value instanceof String ) { StringFormatter fmt = context.getStringFormatter( style .getStringFormat( ) ); text = fmt.format( (String) value ); } else if ( value instanceof Date ) { DateFormatter fmt = context.getDateFormatter( style .getDateFormat( ) ); text = fmt.format( (Date) value ); } else { text = value.toString( ); } } } //text can be null value after applying format if(text!=null) { data.setText( text ); } else { data.setText( "" ); //$NON-NLS-1$ } } /** * handle the label. * * @param label * label content */ public Object visitLabel( ILabelContent label, Object value ) { handleOnRender( label ); processLabel( label ); return label; } /** * process the label content * * <li> localize the help text * <li> localize the label content * <li> handle it as it is an text * * @param label * label object */ protected void processLabel( ILabelContent label ) { String helpText = localize( label, label.getHelpKey( ), label.getHelpText( ) ); label.setHelpText( helpText ); if ( label.getText( ) == null ) { String text = localize( label, label.getLabelKey( ), label.getLabelText( ) ); label.setText( text ); } } public Object visitText( ITextContent text, Object value ) { handleOnRender( text ); return value; } public Object visitForeign( IForeignContent foreignContent, Object value ) { IReportContent reportContent = getReportContent( ); String rawFormat = foreignContent.getRawType( ); Object rawValue = foreignContent.getRawValue( ); if ( IForeignContent.TEMPLATE_TYPE.equals( rawFormat ) ) { handleOnRender( foreignContent ); processTemplateContent( foreignContent ); return foreignContent; } if ( IForeignContent.EXTERNAL_TYPE.equals( rawFormat ) ) { return processExtendedContent( foreignContent ); } if ( IForeignContent.IMAGE_TYPE.equals( rawFormat ) ) { if ( rawValue instanceof IImageContent ) { IImageContent image = (IImageContent) rawValue; processImage( image ); return image; } if ( rawValue instanceof byte[] ) { IImageContent imageContent = reportContent .createImageContent( foreignContent ); imageContent.setImageSource( IImageContent.IMAGE_EXPRESSION ); imageContent.setData( (byte[]) rawValue ); processImage( imageContent ); return imageContent; } } if ( IForeignContent.TEXT_TYPE.equals( rawFormat ) ) { handleOnRender( foreignContent ); ITextContent textContent = reportContent .createDataContent( foreignContent ); textContent.setText( rawValue == null ? "" : rawValue.toString( ) ); //$NON-NLS-1$ return textContent; } if ( IForeignContent.HTML_TYPE.equals( rawFormat ) ) { handleOnRender( foreignContent ); String key = foreignContent.getRawKey( ); if (key != null) { String text = localize( foreignContent, key, null); if (text != null) { foreignContent.setRawValue( text ); } } return foreignContent; } if ( IForeignContent.VALUE_TYPE.equals( rawFormat ) ) { handleOnRender( foreignContent ); IDataContent dataContent = reportContent .createDataContent( foreignContent ); dataContent.setValue( rawValue ); processData( dataContent ); return dataContent; } return foreignContent; } /** * localzie the text. * * @param key * text key * @param text * default text * @return localized text. */ private String localize( IContent content, String key, String text ) { assert ( content != null ); if ( content.getGenerateBy( ) != null ) { DesignElementHandle element = ( (ReportItemDesign) content .getGenerateBy( ) ).getHandle( ); if ( key != null && element != null ) { String t = ModuleUtil.getExternalizedValue( element, key, text, ULocale.forLocale( locale ) ); if ( t != null ) { return t; } } } return text; } public Object visitImage( IImageContent image, Object value ) { handleOnRender( image ); processImage( image ); return image; } protected void processImage( IImageContent image ) { String altText = localize( image, image.getAltTextKey( ), image.getAltText( ) ); image.setAltText( altText ); String helpText = localize( image, image.getHelpKey( ), image.getHelpText( ) ); image.setHelpText( helpText ); } /** * handle the template result. * * @param foreignContent */ protected void processTemplateContent( IForeignContent foreignContent ) { assert IForeignContent.TEMPLATE_TYPE.equals( foreignContent .getRawType( ) ); if ( foreignContent.getGenerateBy( ) instanceof TextItemDesign ) { TextItemDesign design = (TextItemDesign) foreignContent .getGenerateBy( ); String text = null; HashMap rawValues = null; if ( foreignContent.getRawValue( ) instanceof Object[] ) { Object[] rawValue = (Object[]) foreignContent.getRawValue( ); assert rawValue.length == 2; assert rawValue[0] == null || rawValue[0] instanceof String; if ( rawValue[0] != null ) { text = (String )rawValue[0]; } if ( rawValue[1] instanceof HashMap ) { rawValues = (HashMap)rawValue[1]; } } if ( text == null ) { text = localize( foreignContent, design.getTextKey( ), design.getText( ) ); } TextTemplate template = parseTemplate( text ); String result = executeTemplate( template, rawValues ); foreignContent.setRawType( IForeignContent.HTML_TYPE ); foreignContent.setRawValue( result ); } } protected String getOutputFormat() { return outputFormat; } /** * @return whether the output format is for printing */ protected boolean isForPrinting( ) { String outputFormat = getOutputFormat( ); if ( "FO".equalsIgnoreCase( outputFormat ) || "PDF".equalsIgnoreCase( outputFormat ) ||"POSTSCRIPT".equalsIgnoreCase( outputFormat )) return true; return false; } /** * handle an extended item. * * @param content * the object. */ protected IContent processExtendedContent( IForeignContent content ) { assert IForeignContent.EXTERNAL_TYPE.equals( content.getRawType( ) ); assert content.getGenerateBy( ) instanceof ExtendedItemDesign; IContent generatedContent = content; ExtendedItemDesign design = (ExtendedItemDesign) content .getGenerateBy( ); ExtendedItemHandle handle = (ExtendedItemHandle) design.getHandle( ); String tagName = handle.getExtensionName( ); if ( "Chart".equals( tagName ) ) { IHTMLImageHandler imageHandler = context.getImageHandler( ); if ( imageHandler != null ) { String imageId = content.getInstanceID( ).toString( ); CachedImage cachedImage = imageHandler.getCachedImage( imageId, IImage.CUSTOM_IMAGE, context.getReportContext( ) ); if ( cachedImage != null ) { IImageContent imageObj = getReportContent( ) .createImageContent( content ); imageObj.setParent( content.getParent( ) ); // Set image map imageObj.setImageSource( IImageContent.IMAGE_FILE ); imageObj.setURI( cachedImage.getURL( ) ); imageObj.setMIMEType( cachedImage.getMIMEType( ) ); imageObj.setImageMap( cachedImage.getImageMap( ) ); imageObj.setAltText( content.getAltText( ) ); imageObj.setAltTextKey( content.getAltTextKey( ) ); processImage( imageObj ); return imageObj; } } } // call the presentation peer to create the content object IReportItemPresentation itemPresentation = ExtensionManager .getInstance( ).createPresentationItem( tagName ); if ( itemPresentation != null ) { itemPresentation.setModelObject( handle ); itemPresentation.setApplicationClassLoader( context .getApplicationClassLoader( ) ); itemPresentation.setScriptContext( context.getReportContext( ) ); IBaseQueryDefinition[] queries = (IBaseQueryDefinition[])design.getQueries( ); itemPresentation.setReportQueries( queries ); itemPresentation.setDynamicStyle( content.getComputedStyle( ) ); Map appContext = context.getAppContext( ); int resolution = 0; if ( appContext != null ) { Object tmp = appContext.get( EngineConstants.APPCONTEXT_CHART_RESOLUTION ); if ( tmp != null && tmp instanceof Number ) { resolution = ( (Number) tmp ).intValue( ); if ( resolution < 96 ) { resolution = 96; } } } if ( 0 == resolution ) { if ( isForPrinting( ) ) { resolution = 192; } else { resolution = 96; } } itemPresentation.setResolution( resolution ); itemPresentation.setLocale( locale ); String supportedImageFormats = "PNG;GIF;JPG;BMP;"; //$NON-NLS-1$ IRenderOption renderOption = context.getRenderOption( ); String formats = renderOption.getSupportedImageFormats( ); if ( formats != null ) { supportedImageFormats = formats; } itemPresentation.setSupportedImageFormats( supportedImageFormats ); // Default itemPresentation.setActionHandler( context.getActionHandler( ) ); // value String outputFormat = getOutputFormat( ); itemPresentation.setOutputFormat( outputFormat ); Object rawValue = content.getRawValue( ); if ( rawValue instanceof byte[] ) { byte[] values = (byte[]) rawValue; itemPresentation .deserialize( new ByteArrayInputStream( values ) ); } IRowSet[] rowSets = null; IBaseResultSet[] rsets = context.getResultSets(); if ( queries == null ) { DesignElementHandle elementHandle = design.getHandle( ); if ( elementHandle instanceof ReportElementHandle ) { queries = (IBaseQueryDefinition[]) context.getRunnable( ) .getReportIR( ).getQueryByReportHandle( (ReportElementHandle) elementHandle ); } } if ( queries != null ) { if ( rsets != null ) { rowSets = new IRowSet[rsets.length]; for ( int i = 0; i < rowSets.length; i++ ) { rowSets[i] = new RowSet( context, (IQueryResultSet) rsets[i] ); } } } else { if ( rsets != null ) { rowSets = new IRowSet[1]; rowSets[0] = new SingleRowSet( context, (IQueryResultSet) rsets[0] ); } } try { Object output = itemPresentation.onRowSets( rowSets ); if ( output != null ) { int type = itemPresentation.getOutputType( ); String imageMIMEType = itemPresentation.getImageMIMEType( ); generatedContent = processExtendedContent( content, type, output, imageMIMEType ); } itemPresentation.finish( ); } catch ( BirtException ex ) { context.addException( design.getHandle( ), ex ); logger.log( Level.SEVERE, ex.getMessage( ), ex ); } } return generatedContent; } protected IContent processExtendedContent( IForeignContent content, int type, Object output, String imageMIMEType ) { assert IForeignContent.EXTERNAL_TYPE.equals( content.getRawType( ) ); assert output != null; IReportContent reportContent = getReportContent( ); switch ( type ) { case IReportItemPresentation.OUTPUT_NONE : break; case IReportItemPresentation.OUTPUT_AS_IMAGE : case IReportItemPresentation.OUTPUT_AS_IMAGE_WITH_MAP : // the output object is a image, so create a image content // object Object imageMap = null; byte[] imageContent = new byte[0]; Object image = output; if ( type == IReportItemPresentation.OUTPUT_AS_IMAGE_WITH_MAP ) { // OUTPUT_AS_IMAGE_WITH_MAP Object[] imageWithMap = (Object[]) output; if ( imageWithMap.length > 0 ) { image = imageWithMap[0]; } if ( imageWithMap.length > 1 ) { imageMap = imageWithMap[1]; } } if ( image instanceof InputStream ) { imageContent = readContent( (InputStream) image ); } else if ( output instanceof byte[] ) { imageContent = (byte[]) image; } else { assert false; logger.log( Level.WARNING, "unsupported image type:{0}", output ); //$NON-NLS-1$ } IImageContent imageObj = reportContent.createImageContent( content ); imageObj.setParent( content.getParent( ) ); // Set image map imageObj.setImageSource( IImageContent.IMAGE_EXPRESSION ); imageObj.setData( imageContent ); imageObj.setImageMap( imageMap ); imageObj.setMIMEType( imageMIMEType ); imageObj.setAltText( content.getAltText( ) ); imageObj.setAltTextKey( content.getAltTextKey( ) ); processImage( imageObj ); return imageObj; case IReportItemPresentation.OUTPUT_AS_CUSTOM : IDataContent dataObj = reportContent.createDataContent( content ); dataObj.setValue( output ); processData( dataObj ); return dataObj; case IReportItemPresentation.OUTPUT_AS_HTML_TEXT : content.setRawType( IForeignContent.HTML_TYPE ); content.setRawValue( output.toString( ) ); return content; case IReportItemPresentation.OUTPUT_AS_TEXT : ITextContent textObj = reportContent.createTextContent( ); textObj.setText( output.toString( ) ); return textObj; default : assert false; logger.log( Level.WARNING, "unsupported output format:{0}", //$NON-NLS-1$ new Integer( type ) ); } return content; } /** * read the content of input stream. * * @param in * input content * @return content in the stream. */ static protected byte[] readContent( InputStream in ) { BufferedInputStream bin = in instanceof BufferedInputStream ? (BufferedInputStream) in : new BufferedInputStream( in ); ByteArrayOutputStream out = new ByteArrayOutputStream( 1024 ); byte[] buffer = new byte[1024]; int readSize = 0; try { readSize = bin.read( buffer ); while ( readSize != -1 ) { out.write( buffer, 0, readSize ); readSize = bin.read( buffer ); } } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); } return out.toByteArray( ); } protected void handleOnRender( IContent content ) { if ( content.getGenerateBy( ) != null ) { onRenderVisitor.onRender( content ); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1275"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.cyclops.integrateddynamics.part.aspect.write; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import net.minecraft.block.state.IBlockState; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemStack; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.event.world.NoteBlockEvent; import net.minecraftforge.fluids.FluidStack; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import org.cyclops.integrateddynamics.api.evaluate.EvaluationException; import org.cyclops.integrateddynamics.api.evaluate.variable.IValue; import org.cyclops.integrateddynamics.api.evaluate.variable.IValueType; import org.cyclops.integrateddynamics.api.evaluate.variable.IVariable; import org.cyclops.integrateddynamics.api.part.PartTarget; import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties; import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectPropertyTypeInstance; import org.cyclops.integrateddynamics.api.part.write.IPartStateWriter; import org.cyclops.integrateddynamics.api.part.write.IPartTypeWriter; import org.cyclops.integrateddynamics.core.evaluate.variable.*; import org.cyclops.integrateddynamics.core.part.aspect.build.AspectBuilder; import org.cyclops.integrateddynamics.core.part.aspect.build.IAspectValuePropagator; import org.cyclops.integrateddynamics.core.part.aspect.build.IAspectWriteDeactivator; import org.cyclops.integrateddynamics.core.part.aspect.property.AspectProperties; import org.cyclops.integrateddynamics.core.part.aspect.property.AspectPropertyTypeInstance; import org.cyclops.integrateddynamics.part.aspect.read.AspectReadBuilders; import org.cyclops.integrateddynamics.part.aspect.write.redstone.IWriteRedstoneComponent; import org.cyclops.integrateddynamics.part.aspect.write.redstone.WriteRedstoneComponent; import java.util.List; /** * Collection of aspect write builders and value propagators. * @author rubensworks */ public class AspectWriteBuilders { public static final AspectBuilder<ValueTypeBoolean.ValueBoolean, ValueTypeBoolean, Triple<PartTarget, IAspectProperties, ValueTypeBoolean.ValueBoolean>> BUILDER_BOOLEAN = getValue(AspectBuilder.forWriteType(ValueTypes.BOOLEAN)); public static final AspectBuilder<ValueTypeInteger.ValueInteger, ValueTypeInteger, Triple<PartTarget, IAspectProperties, ValueTypeInteger.ValueInteger>> BUILDER_INTEGER = getValue(AspectBuilder.forWriteType(ValueTypes.INTEGER)); public static final AspectBuilder<ValueTypeDouble.ValueDouble, ValueTypeDouble, Triple<PartTarget, IAspectProperties, ValueTypeDouble.ValueDouble>> BUILDER_DOUBLE = getValue(AspectBuilder.forWriteType(ValueTypes.DOUBLE)); public static final AspectBuilder<ValueTypeString.ValueString, ValueTypeString, Triple<PartTarget, IAspectProperties, ValueTypeString.ValueString>> BUILDER_STRING = getValue(AspectBuilder.forWriteType(ValueTypes.STRING)); public static final AspectBuilder<ValueTypeList.ValueList, ValueTypeList, Triple<PartTarget, IAspectProperties, ValueTypeList.ValueList>> BUILDER_LIST = getValue(AspectBuilder.forWriteType(ValueTypes.LIST)); public static final AspectBuilder<ValueObjectTypeItemStack.ValueItemStack, ValueObjectTypeItemStack, Triple<PartTarget, IAspectProperties, ValueObjectTypeItemStack.ValueItemStack>> BUILDER_ITEMSTACK = getValue(AspectBuilder.forWriteType(ValueTypes.OBJECT_ITEMSTACK)); public static final AspectBuilder<ValueObjectTypeFluidStack.ValueFluidStack, ValueObjectTypeFluidStack, Triple<PartTarget, IAspectProperties, ValueObjectTypeFluidStack.ValueFluidStack>> BUILDER_FLUIDSTACK = getValue(AspectBuilder.forWriteType(ValueTypes.OBJECT_FLUIDSTACK)); public static final AspectBuilder<ValueTypeOperator.ValueOperator, ValueTypeOperator, Triple<PartTarget, IAspectProperties, ValueTypeOperator.ValueOperator>> BUILDER_OPERATOR = getValue(AspectBuilder.forWriteType(ValueTypes.OPERATOR)); public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeBoolean.ValueBoolean>, Triple<PartTarget, IAspectProperties, Boolean>> PROP_GET_BOOLEAN = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeBoolean.ValueBoolean>, Triple<PartTarget, IAspectProperties, Boolean>>() { @Override public Triple<PartTarget, IAspectProperties, Boolean> getOutput(Triple<PartTarget, IAspectProperties, ValueTypeBoolean.ValueBoolean> input) throws EvaluationException { return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue()); } }; public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties,ValueTypeInteger.ValueInteger>, Triple<PartTarget, IAspectProperties, Integer>> PROP_GET_INTEGER = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeInteger.ValueInteger>, Triple<PartTarget, IAspectProperties, Integer>>() { @Override public Triple<PartTarget, IAspectProperties, Integer> getOutput(Triple<PartTarget, IAspectProperties, ValueTypeInteger.ValueInteger> input) throws EvaluationException { return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue()); } }; public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeDouble.ValueDouble>, Triple<PartTarget, IAspectProperties, Double>> PROP_GET_DOUBLE = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeDouble.ValueDouble>, Triple<PartTarget, IAspectProperties, Double>>() { @Override public Triple<PartTarget, IAspectProperties, Double> getOutput(Triple<PartTarget, IAspectProperties, ValueTypeDouble.ValueDouble> input) throws EvaluationException { return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue()); } }; public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeLong.ValueLong>, Triple<PartTarget, IAspectProperties, Long>> PROP_GET_LONG = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeLong.ValueLong>, Triple<PartTarget, IAspectProperties, Long>>() { @Override public Triple<PartTarget, IAspectProperties, Long> getOutput(Triple<PartTarget, IAspectProperties, ValueTypeLong.ValueLong> input) throws EvaluationException { return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue()); } }; public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeItemStack.ValueItemStack>, Triple<PartTarget, IAspectProperties, ItemStack>> PROP_GET_ITEMSTACK = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeItemStack.ValueItemStack>, Triple<PartTarget, IAspectProperties, ItemStack>>() { @Override public Triple<PartTarget, IAspectProperties, ItemStack> getOutput(Triple<PartTarget, IAspectProperties, ValueObjectTypeItemStack.ValueItemStack> input) throws EvaluationException { ItemStack optional = input.getRight().getRawValue(); return Triple.of(input.getLeft(), input.getMiddle(), !optional.isEmpty() ? optional : null); } }; public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeString.ValueString>, Triple<PartTarget, IAspectProperties, String>> PROP_GET_STRING = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeString.ValueString>, Triple<PartTarget, IAspectProperties, String>>() { @Override public Triple<PartTarget, IAspectProperties, String> getOutput(Triple<PartTarget, IAspectProperties, ValueTypeString.ValueString> input) throws EvaluationException { return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue()); } }; public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeBlock.ValueBlock>, Triple<PartTarget, IAspectProperties, IBlockState>> PROP_GET_BLOCK = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeBlock.ValueBlock>, Triple<PartTarget, IAspectProperties, IBlockState>>() { @Override public Triple<PartTarget, IAspectProperties, IBlockState> getOutput(Triple<PartTarget, IAspectProperties, ValueObjectTypeBlock.ValueBlock> input) throws EvaluationException { Optional<IBlockState> optional = input.getRight().getRawValue(); return Triple.of(input.getLeft(), input.getMiddle(), optional.isPresent() ? optional.get() : null); } }; public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeFluidStack.ValueFluidStack>, Triple<PartTarget, IAspectProperties, FluidStack>> PROP_GET_FLUIDSTACK = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeFluidStack.ValueFluidStack>, Triple<PartTarget, IAspectProperties, FluidStack>>() { @Override public Triple<PartTarget, IAspectProperties, FluidStack> getOutput(Triple<PartTarget, IAspectProperties, ValueObjectTypeFluidStack.ValueFluidStack> input) throws EvaluationException { Optional<FluidStack> optional = input.getRight().getRawValue(); return Triple.of(input.getLeft(), input.getMiddle(), optional.isPresent() ? optional.get() : null); } }; public static final class Audio { public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_VOLUME = new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.volume.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE); public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_FREQUENCY = new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.frequency.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE); public static final IAspectProperties PROPERTIES_NOTE = new AspectProperties(Sets.<IAspectPropertyTypeInstance>newHashSet( PROP_VOLUME )); public static final IAspectProperties PROPERTIES_SOUND = new AspectProperties(ImmutableList.<IAspectPropertyTypeInstance>of( PROP_VOLUME, PROP_FREQUENCY )); static { Predicate<ValueTypeDouble.ValueDouble> POSITIVE = new Predicate<ValueTypeDouble.ValueDouble>() { @Override public boolean apply(ValueTypeDouble.ValueDouble input) { return input.getRawValue() >= 0; } }; PROPERTIES_NOTE.setValue(PROP_VOLUME, ValueTypeDouble.ValueDouble.of(3D)); PROPERTIES_SOUND.setValue(PROP_VOLUME, ValueTypeDouble.ValueDouble.of(3D)); PROPERTIES_SOUND.setValue(PROP_FREQUENCY, ValueTypeDouble.ValueDouble.of(1D)); } private static final List<SoundEvent> INSTRUMENTS = Lists.newArrayList(new SoundEvent[] {SoundEvents.BLOCK_NOTE_HARP, SoundEvents.BLOCK_NOTE_BASEDRUM, SoundEvents.BLOCK_NOTE_SNARE, SoundEvents.BLOCK_NOTE_HAT, SoundEvents.BLOCK_NOTE_BASS}); private static SoundEvent getInstrument(int id) { if (id < 0 || id >= INSTRUMENTS.size()) { id = 0; } return INSTRUMENTS.get(id); } public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>>, Void> PROP_SET = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>>, Void>() { @Override public Void getOutput(Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>> input) { IAspectProperties properties = input.getMiddle(); BlockPos pos = input.getLeft().getTarget().getPos().getBlockPos(); int eventID = input.getRight().getLeft().ordinal(); int eventParam = input.getRight().getRight(); if(eventParam >= 0 && eventParam <= 24) { World world = input.getLeft().getTarget().getPos().getWorld(); NoteBlockEvent.Play e = new NoteBlockEvent.Play(world, pos, world.getBlockState(pos), eventParam, eventID); if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(e)) { float f = (float) Math.pow(2.0D, (double) (eventParam - 12) / 12.0D); float volume = (float) properties.getValue(PROP_VOLUME).getRawValue(); world.playSound(null, (double) pos.getX() + 0.5D, (double) pos.getY() + 0.5D, (double) pos.getZ() + 0.5D, getInstrument(eventID), SoundCategory.RECORDS, volume, f); } } return null; } }; public static IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Integer>, Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>>> propWithInstrument(final NoteBlockEvent.Instrument instrument) { return new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Integer>, Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>>>() { @Override public Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>> getOutput(Triple<PartTarget, IAspectProperties, Integer> input) throws EvaluationException { return Triple.of(input.getLeft(), input.getMiddle(), Pair.of(instrument, input.getRight())); } }; } public static final AspectBuilder<ValueTypeInteger.ValueInteger, ValueTypeInteger, Triple<PartTarget, IAspectProperties, Integer>> BUILDER_INTEGER = AspectWriteBuilders.BUILDER_INTEGER.appendKind("audio").handle(PROP_GET_INTEGER); public static final AspectBuilder<ValueTypeInteger.ValueInteger, ValueTypeInteger, Triple<PartTarget, IAspectProperties, Integer>> BUILDER_INTEGER_INSTRUMENT = BUILDER_INTEGER.appendKind("instrument").withProperties(PROPERTIES_NOTE); public static final AspectBuilder<ValueTypeString.ValueString, ValueTypeString, Triple<PartTarget, IAspectProperties, String>> BUILDER_STRING = AspectWriteBuilders.BUILDER_STRING.appendKind("audio").handle(PROP_GET_STRING); } public static final class Effect { public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_OFFSET_X = new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.offset_x.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE); public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_OFFSET_Y = new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.offset_y.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE); public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_OFFSET_Z = new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.offset_z.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE); public static final IAspectPropertyTypeInstance<ValueTypeInteger, ValueTypeInteger.ValueInteger> PROP_PARTICLES = new AspectPropertyTypeInstance<>(ValueTypes.INTEGER, "aspect.aspecttypes.integrateddynamics.integer.particles.name", AspectReadBuilders.VALIDATOR_INTEGER_POSITIVE); public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_SPREAD_X = new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.spread_x.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE); public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_SPREAD_Y = new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.spread_y.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE); public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_SPREAD_Z = new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.spread_z.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE); public static final IAspectPropertyTypeInstance<ValueTypeBoolean, ValueTypeBoolean.ValueBoolean> PROP_FORCE = new AspectPropertyTypeInstance<>(ValueTypes.BOOLEAN, "aspect.aspecttypes.integrateddynamics.boolean.force_particle.name"); public static final IAspectProperties PROPERTIES_PARTICLE = new AspectProperties(ImmutableList.<IAspectPropertyTypeInstance>of( PROP_OFFSET_X, PROP_OFFSET_Y, PROP_OFFSET_Z, PROP_PARTICLES, PROP_SPREAD_X, PROP_SPREAD_Y, PROP_SPREAD_Z, PROP_FORCE )); static { PROPERTIES_PARTICLE.setValue(PROP_OFFSET_X, ValueTypeDouble.ValueDouble.of(0.5D)); PROPERTIES_PARTICLE.setValue(PROP_OFFSET_Z, ValueTypeDouble.ValueDouble.of(0.5D)); PROPERTIES_PARTICLE.setValue(PROP_OFFSET_Y, ValueTypeDouble.ValueDouble.of(0.5D)); PROPERTIES_PARTICLE.setValue(PROP_PARTICLES, ValueTypeInteger.ValueInteger.of(1)); PROPERTIES_PARTICLE.setValue(PROP_SPREAD_X, ValueTypeDouble.ValueDouble.of(0.0D)); PROPERTIES_PARTICLE.setValue(PROP_SPREAD_Y, ValueTypeDouble.ValueDouble.of(0.0D)); PROPERTIES_PARTICLE.setValue(PROP_SPREAD_Z, ValueTypeDouble.ValueDouble.of(0.0D)); PROPERTIES_PARTICLE.setValue(PROP_FORCE, ValueTypeBoolean.ValueBoolean.of(false)); } public static final AspectBuilder<ValueTypeDouble.ValueDouble, ValueTypeDouble, Triple<PartTarget, IAspectProperties, Double>> BUILDER_DOUBLE = AspectWriteBuilders.BUILDER_DOUBLE.appendKind("effect").handle(PROP_GET_DOUBLE); public static final AspectBuilder<ValueTypeDouble.ValueDouble, ValueTypeDouble, Triple<PartTarget, IAspectProperties, Double>> BUILDER_DOUBLE_PARTICLE = BUILDER_DOUBLE.withProperties(PROPERTIES_PARTICLE); } public static final class Redstone { private static final IWriteRedstoneComponent WRITE_REDSTONE_COMPONENT = new WriteRedstoneComponent(); public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Integer>, Void> PROP_SET = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Integer>, Void>() { @Override public Void getOutput(Triple<PartTarget, IAspectProperties, Integer> input) { boolean strongPower = input.getMiddle().getValue(PROP_STRONG_POWER).getRawValue(); WRITE_REDSTONE_COMPONENT.setRedstoneLevel(input.getLeft(), input.getRight(), strongPower); return null; } }; public static final IAspectWriteDeactivator DEACTIVATOR = new IAspectWriteDeactivator() { @Override public <P extends IPartTypeWriter<P, S>, S extends IPartStateWriter<P>> void onDeactivate(P partType, PartTarget target, S state) { WRITE_REDSTONE_COMPONENT.deactivate(target); } }; public static final IAspectPropertyTypeInstance<ValueTypeBoolean, ValueTypeBoolean.ValueBoolean> PROP_STRONG_POWER = new AspectPropertyTypeInstance<>(ValueTypes.BOOLEAN, "aspect.aspecttypes.integrateddynamics.boolean.strong_power.name"); public static final IAspectProperties PROPERTIES_REDSTONE = new AspectProperties(ImmutableList.<IAspectPropertyTypeInstance>of( PROP_STRONG_POWER )); static { PROPERTIES_REDSTONE.setValue(PROP_STRONG_POWER, ValueTypeBoolean.ValueBoolean.of(false)); } public static final AspectBuilder<ValueTypeBoolean.ValueBoolean, ValueTypeBoolean, Triple<PartTarget, IAspectProperties, Boolean>> BUILDER_BOOLEAN = AspectWriteBuilders.BUILDER_BOOLEAN.appendKind("redstone").handle(PROP_GET_BOOLEAN).appendDeactivator(DEACTIVATOR).withProperties(PROPERTIES_REDSTONE); public static final AspectBuilder<ValueTypeInteger.ValueInteger, ValueTypeInteger, Triple<PartTarget, IAspectProperties, Integer>> BUILDER_INTEGER = AspectWriteBuilders.BUILDER_INTEGER.appendKind("redstone").handle(PROP_GET_INTEGER).appendDeactivator(DEACTIVATOR).withProperties(PROPERTIES_REDSTONE); } public static <V extends IValue, T extends IValueType<V>> AspectBuilder<V, T, Triple<PartTarget, IAspectProperties, V>> getValue(AspectBuilder<V, T, Triple<PartTarget, IAspectProperties, IVariable<V>>> builder) { return builder.handle(new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, IVariable<V>>, Triple<PartTarget, IAspectProperties, V>>() { @Override public Triple<PartTarget, IAspectProperties, V> getOutput(Triple<PartTarget, IAspectProperties, IVariable<V>> input) throws EvaluationException { return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getValue()); } }); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1276"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.wikipathways.wp2rdf; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import org.bridgedb.DataSource; import org.bridgedb.IDMapperException; import org.bridgedb.IDMapperStack; import org.bridgedb.bio.DataSourceTxt; import org.junit.Assert; import org.junit.Test; import org.pathvisio.core.model.ConverterException; import org.pathvisio.core.model.Pathway; import org.wikipathways.wp2rdf.io.PathwayReader; public abstract class AbstractWPConvertorTest extends AbstractConvertorTest { public static void loadModelAsWPRDF(String gpmlFile, String wpid, String revision) throws ConverterException, FileNotFoundException, ClassNotFoundException, IOException, IDMapperException { DataSourceTxt.init(); // the next line is needed until BridgeDb gets updated DataSource.register("Cpx", "Complex Portal") .identifiersOrgBase("http://identifiers.org/complexportal/") .asDataSource(); DataSource.register("Pbd", "Digital Object Identifier").asDataSource(); DataSource.register("Pbm", "PubMed").asDataSource(); DataSource.register("Gpl", "Guide to Pharmacology Targets").asDataSource(); InputStream input = AbstractConvertorTest.class.getClassLoader().getResourceAsStream(gpmlFile); Pathway pathway = PathwayReader.readPathway(input); Assert.assertNotNull(pathway); IDMapperStack stack = WPREST2RDF.maps(); model = GpmlConverter.convertWp(pathway, wpid, revision, stack, Collections.<String>emptyList()); Assert.assertNotNull(model); // String ttlContent = toString(model); // if (ttlContent.length() > 1000) ttlContent.substring(0,1000); // System.out.println(ttlContent); } @Test public void untypedPubMedRef() throws Exception { String sparql = ResourceHelper.resourceAsString("structure/untypedPubMedRefs.rq"); StringMatrix table = SPARQLHelper.sparql(model, sparql); Assert.assertNotNull(table); Assert.assertEquals("No tping as wp:PublicationReference for PubMed URIs:\n" + table, 0, table.getRowCount()); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1277"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.jivesoftware.smackx; import java.util.*; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smackx.packet.DataForm; /** * Represents a Form for gathering data. The form could be of the following types: * <ul> * <li>form -> Indicates a form to fill out.</li> * <li>submit -> The form is filled out, and this is the data that is being returned from * the form.</li> * <li>cancel -> The form was cancelled. Tell the asker that piece of information.</li> * <li>result -> Data results being returned from a search, or some other query.</li> * </ul> * * Depending of the form's type different operations are available. For example, it's only possible * to set answers if the form is of type "submit". * * @author Gaston Dombiak */ public class Form { public static final String TYPE_FORM = "form"; public static final String TYPE_SUBMIT = "submit"; public static final String TYPE_CANCEL = "cancel"; public static final String TYPE_RESULT = "result"; private DataForm dataForm; /** * Returns a new ReportedData if the packet is used for gathering data and includes an * extension that matches the elementName and namespace "x","jabber:x:data". * * @param packet the packet used for gathering data. */ public static Form getFormFrom(Packet packet) { // Check if the packet includes the DataForm extension PacketExtension packetExtension = packet.getExtension("x","jabber:x:data"); if (packetExtension != null) { // Check if the existing DataForm is not a result of a search DataForm dataForm = (DataForm) packetExtension; if (dataForm.getReportedData() == null) return new Form(dataForm); } // Otherwise return null return null; } /** * Creates a new Form that will wrap an existing DataForm. The wrapped DataForm must be * used for gathering data. * * @param dataForm the data form used for gathering data. */ private Form(DataForm dataForm) { this.dataForm = dataForm; } /** * Creates a new Form of a given type from scratch.<p> * * Possible form types are: * <ul> * <li>form -> Indicates a form to fill out.</li> * <li>submit -> The form is filled out, and this is the data that is being returned from * the form.</li> * <li>cancel -> The form was cancelled. Tell the asker that piece of information.</li> * <li>result -> Data results being returned from a search, or some other query.</li> * </ul> * * @param type the form's type (e.g. form, submit,cancel,result). */ public Form(String type) { this.dataForm = new DataForm(type); } /** * Adds a new field to complete as part of the form. * * @param field the field to complete. */ public void addField(FormField field) { dataForm.addField(field); } public void setAnswer(String variable, String value) { if (!isSubmitType()) { throw new IllegalStateException("Cannot set an answer if the form is not of type " + "\"submit\""); } FormField field = getField(variable); if (field != null) { field.resetValues(); field.addValue(value); } else { throw new IllegalArgumentException("Couldn't find a field for the specified variable."); } } public void setAnswer(String variable, List values) { if (!isSubmitType()) { throw new IllegalStateException("Cannot set an answer if the form is not of type " + "\"submit\""); } FormField field = getField(variable); if (field != null) { field.resetValues(); field.addValues(values); } else { throw new IllegalArgumentException("Couldn't find a field for the specified variable."); } } /** * Returns an Iterator for the fields that are part of the form. * * @return an Iterator for the fields that are part of the form. */ public Iterator getFields() { return dataForm.getFields(); } /** * Returns the field of the form whose variable matches the specified variable. * The fields of type FIXED will never be returned since they do not specify a * variable. * * @param variable the variable to look for in the form fields. * @return the field of the form whose variable matches the specified variable. */ public FormField getField(String variable) { if (variable == null || variable.equals("")) { throw new IllegalArgumentException("Variable must not be null or blank."); } // Look for the field whose variable matches the requested variable FormField field; for (Iterator it=getFields();it.hasNext();) { field = (FormField)it.next(); if (variable.equals(field.getVariable())) { return field; } } return null; } /** * Returns the instructions that explain how to fill out the form and what the form is about. * * @return instructions that explain how to fill out the form. */ public String getInstructions() { return dataForm.getInstructions(); } /** * Returns the description of the data. It is similar to the title on a web page or an X * window. You can put a <title/> on either a form to fill out, or a set of data results. * * @return description of the data. */ public String getTitle() { return dataForm.getTitle(); } /** * Returns the meaning of the data within the context. The data could be part of a form * to fill out, a form submission or data results.<p> * * Possible form types are: * <ul> * <li>form -> Indicates a form to fill out.</li> * <li>submit -> The form is filled out, and this is the data that is being returned from * the form.</li> * <li>cancel -> The form was cancelled. Tell the asker that piece of information.</li> * <li>result -> Data results being returned from a search, or some other query.</li> * </ul> * * @return the form's type. */ public String getType() { return dataForm.getType(); } /** * Sets instructions that explain how to fill out the form and what the form is about. * * @param instructions instructions that explain how to fill out the form. */ public void setInstructions(String instructions) { dataForm.setInstructions(instructions); } /** * Sets the description of the data. It is similar to the title on a web page or an X window. * You can put a <title/> on either a form to fill out, or a set of data results. * * @param title description of the data. */ public void setTitle(String title) { dataForm.setTitle(title); } /** * Returns a DataForm that serves to send this Form to the server. If the form is of type * submit, it may contain fields with no value. These fields will be remove since they only * exist to assist the user while editing/completing the form in a UI. * * @return the wrapped DataForm. */ DataForm getDataFormToSend() { if (isSubmitType()) { // Answer a new form based on the values of this form DataForm dataFormToSend = new DataForm(getType()); dataFormToSend.setInstructions(getInstructions()); dataFormToSend.setTitle(getTitle()); // Remove all the fields that have no answer for(Iterator it=getFields();it.hasNext();) { FormField field = (FormField)it.next(); if (field.getValues().hasNext()) { dataFormToSend.addField(field); } } return dataFormToSend; } return dataForm; } /** * Returns true if the form is a form to fill out. * * @return if the form is a form to fill out. */ private boolean isFormType() { return TYPE_FORM.equals(dataForm.getType()); } /** * Returns true if the form is a form to submit. * * @return if the form is a form to submit. */ private boolean isSubmitType() { return TYPE_SUBMIT.equals(dataForm.getType()); } /** * Returns a new Form to submit the completed values. The new Form will include all the fields * of the original form except for the fields of type FIXED. Only the HIDDEN fields will * include the same value of the original form. The other fields of the new form MUST be * completed. If a field remains with no answer when sending the completed form, then it won't * be included as part of the completed form.<p> * * The reason why the fields with variables are included in the new form is to provide a model * for binding with any UI. This means that the UIs will use the original form (of type * "form") to learn how to render the form, but the UIs will bind the fields to the form of * type submit. * * @return a Form to submit the completed values. */ public Form createAnswerForm() { if (!isFormType()) { throw new IllegalStateException("Only forms of type \"form\" could be answered"); } // Create a new Form Form form = new Form(TYPE_SUBMIT); for (Iterator fields=getFields(); fields.hasNext();) { FormField field = (FormField)fields.next(); // Add to the new form any type of field that includes a variable. // Note: The fields of type FIXED are the only ones that don't specify a variable if (field.getVariable() != null) { form.addField(new FormField(field.getVariable())); // Set the answer ONLY to the hidden fields if (FormField.TYPE_HIDDEN.equals(field.getType())) { // Since a hidden field could have many values we need to collect them // in a list List values = new ArrayList(); for (Iterator it=field.getValues();it.hasNext();) { values.add((String)it.next()); } form.setAnswer(field.getVariable(), values); } } } return form; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1278"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package ru.tuin; /** * @author Viktor Tulin * @version 1 * @since 27.10.2016 */ public class StartUI { private Calculator calc; private ConsoleInput input; private InteractCalculator menu; public StartUI(ConsoleInput input, Calculator calc, InteractCalculator menu) { this.calc = calc; this.input = input; this.menu = menu; } /** * method displays a menu until the user does not want to leave the program */ public void init() { do { menu.show(); int entry = this.input.ask("\nselect the menu item: ", menu.getAcceptableRange()); menu.select(Key.getKeyFromNumber(entry)); } while (!"y".equals(this.input.ask("To exit the program press (y) To continue work press (Enter): "))); } public static void main(String[] args) { EngineerCalculator calc = new EngineerCalculator(); ConsoleInput input = new ValidateInput(); Print print = new Print(); EngineerInteractCalculator menu = new EngineerInteractCalculator(input, calc, print); new StartUI(input, calc, menu).init(); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1279"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.cyclops.structuredcrafting.craft.provider; import com.mojang.authlib.GameProfile; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import org.cyclops.cyclopscore.helper.BlockEntityHelpers; import org.cyclops.cyclopscore.helper.ItemStackHelpers; import org.cyclops.structuredcrafting.block.BlockStructuredCrafterConfig; import java.util.Map; import java.util.UUID; import java.util.WeakHashMap; /** * World that can provide an itemstack. * @author rubensworks */ public class WorldItemStackProvider implements IItemStackProvider { private static GameProfile PROFILE = new GameProfile(UUID.fromString("41C82C87-7AfB-4024-BB57-13D2C99CAE78"), "[StructuredCrafting]"); private static final Map<ServerLevel, FakePlayer> FAKE_PLAYERS = new WeakHashMap<ServerLevel, FakePlayer>(); public static FakePlayer getFakePlayer(ServerLevel world) { FakePlayer fakePlayer = FAKE_PLAYERS.get(world); if (fakePlayer == null) { fakePlayer = new FakePlayer(world, PROFILE); FAKE_PLAYERS.put(world, fakePlayer); } return fakePlayer; } @Override public boolean canProvideInput() { return BlockStructuredCrafterConfig.canTakeInputsFromWorld; } @Override public boolean canHandleOutput() { return BlockStructuredCrafterConfig.canPlaceOutputsIntoWorld; } @Override public boolean isValidForResults(Level world, BlockPos pos, Direction side) { return world.isEmptyBlock(pos); } protected boolean hasEmptyItemHandler(Level world, BlockPos pos, Direction side) { IItemHandler itemHandler = BlockEntityHelpers.getCapability(world, pos, side, CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).orElse(null); boolean emptyItemHandler = true; if (itemHandler != null) { for (int i = 0; i < itemHandler.getSlots(); i++) { if (!itemHandler.extractItem(i, 1, true).isEmpty()) { emptyItemHandler = false; break; } } } return emptyItemHandler; } @Override public boolean hasItemStack(Level world, BlockPos pos, Direction side) { return !world.isEmptyBlock(pos) && hasEmptyItemHandler(world, pos, side); } @Override public ItemStack getItemStack(Level world, BlockPos pos, Direction side) { BlockState blockState = world.getBlockState(pos); if(blockState != null && hasEmptyItemHandler(world, pos, side)) { return blockState.getCloneItemStack(new BlockHitResult(new Vec3(0, 0, 0), side, pos, false), world, pos, getFakePlayer((ServerLevel) world)); } return ItemStack.EMPTY; } @Override public void reduceItemStack(Level world, BlockPos pos, Direction side, boolean simulate) { if(!simulate) { world.removeBlock(pos, false); } } @Override public boolean addItemStack(Level world, BlockPos pos, Direction side, ItemStack itemStack, boolean simulate) { return setItemStack(world, pos, side, itemStack, simulate); } @Override public boolean setItemStack(Level world, BlockPos pos, Direction side, ItemStack itemStack, boolean simulate) { if(!simulate && itemStack.getItem() instanceof BlockItem) { world.setBlockAndUpdate(pos, ((BlockItem) itemStack.getItem()).getBlock().defaultBlockState()); itemStack.shrink(1); } if(!simulate && itemStack.getCount() > 0) { ItemStackHelpers.spawnItemStack(world, pos, itemStack); } return true; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1280"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package de.vanmar.android.yarrn.requests; import android.app.Application; import com.octo.android.robospice.persistence.DurationInMillis; import com.octo.android.robospice.persistence.exception.SpiceException; import com.octo.android.robospice.persistence.springandroid.json.gson.GsonObjectPersisterFactory; import org.acra.ACRA; import org.scribe.model.OAuthRequest; import org.scribe.model.Response; import de.vanmar.android.yarrn.YarrnPrefs_; import de.vanmar.android.yarrn.ravelry.dts.ETaggable; public abstract class AbstractRavelryGetRequest<T extends ETaggable> extends AbstractRavelryRequest<T> { public static final long CACHE_DURATION = DurationInMillis.ONE_MINUTE; private final GsonObjectPersisterFactory persisterFactory; public AbstractRavelryGetRequest(Class<T> clazz, Application application, YarrnPrefs_ prefs) { super(clazz, prefs, application); try { persisterFactory = new GsonObjectPersisterFactory(application); } catch (SpiceException e) { e.printStackTrace(); throw new RuntimeException(e); } } @Override public T loadDataFromNetwork() throws Exception { final OAuthRequest request = getRequest(); ACRA.getErrorReporter().putCustomData("lastUrl", getCacheKey().toString()); /*T dataFromCache = persisterFactory.createObjectPersister(getResultType()).loadDataFromCache(getCacheKey(), DurationInMillis.ALWAYS_RETURNED); if (dataFromCache != null) { request.addHeader("If-None-Match", dataFromCache.getETag()); }*/ final Response response = executeRequest(request); /*if (response.getCode() == 304) { return dataFromCache; } else {*/ T result = parseResult(response.getBody()); result.setETag(response.getHeader("ETag")); return result; } protected abstract T parseResult(String responseBody); protected abstract OAuthRequest getRequest(); public Object getCacheKey() { OAuthRequest request = getRequest(); return request.getCompleteUrl(); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1281"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.jenkinsci.plugins.docker.commons.impl; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import javax.annotation.Nonnull; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import hudson.AbortException; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.model.TaskListener; import hudson.util.ArgumentListBuilder; import net.sf.json.JSONObject; /** * Logs you in to a Docker registry. */ @Restricted(NoExternalUse.class) public class RegistryKeyMaterialFactory extends KeyMaterialFactory { private static final String DOCKER_CONFIG_FILENAME = "config.json"; private static final String[] BLACKLISTED_PROPERTIES = { "auths", "credsStore" }; private final @Nonnull String username; private final @Nonnull String password; private final @Nonnull URL endpoint; private final @Nonnull Launcher launcher; private final @Nonnull EnvVars env; private final @Nonnull TaskListener listener; private final @Nonnull String dockerExecutable; public RegistryKeyMaterialFactory(@Nonnull String username, @Nonnull String password, @Nonnull URL endpoint, @Nonnull Launcher launcher, @Nonnull EnvVars env, @Nonnull TaskListener listener, @Nonnull String dockerExecutable) { this.username = username; this.password = password; this.endpoint = endpoint; this.launcher = launcher; this.env = env; this.listener = listener; this.dockerExecutable = dockerExecutable; } @Override public KeyMaterial materialize() throws IOException, InterruptedException { FilePath dockerConfig = createSecretsDirectory(); // read the existing docker config file, which might hold some important settings (e.b. proxies) FilePath configJsonPath = FilePath.getHomeDirectory(this.launcher.getChannel()).child(".docker").child(DOCKER_CONFIG_FILENAME); if (configJsonPath.exists()) { String configJson = configJsonPath.readToString(); if (StringUtils.isNotBlank(configJson)) { launcher.getListener().getLogger().print("Using the existing docker config file."); JSONObject json = JSONObject.fromObject(configJson); for (String property : BLACKLISTED_PROPERTIES) { Object value = json.remove(property); if (value != null) { launcher.getListener().getLogger().print("Removing blacklisted property: " + property); } } dockerConfig.child(DOCKER_CONFIG_FILENAME).write(json.toString(), StandardCharsets.UTF_8.name()); } } try { EnvVars envWithConfig = new EnvVars(env); envWithConfig.put("DOCKER_CONFIG", dockerConfig.getRemote()); if (launcher.launch().cmds(new ArgumentListBuilder(dockerExecutable, "login", "-u", username, "--password-stdin").add(endpoint)).envs(envWithConfig).stdin(new ByteArrayInputStream(password.getBytes("UTF-8"))).stdout(listener).join() != 0) { throw new AbortException("docker login failed"); } } catch (IOException | InterruptedException x) { try { dockerConfig.deleteRecursive(); } catch (Exception x2) { x.addSuppressed(x2); } throw x; } return new RegistryKeyMaterial(dockerConfig, new EnvVars("DOCKER_CONFIG", dockerConfig.getRemote())); } private static class RegistryKeyMaterial extends KeyMaterial { private final FilePath dockerConfig; RegistryKeyMaterial(FilePath dockerConfig, EnvVars envVars) { super(envVars); this.dockerConfig = dockerConfig; } @Override public void close() throws IOException { try { dockerConfig.deleteRecursive(); } catch (InterruptedException x) { // TODO would better have been thrown from KeyMaterial.close to begin with throw new IOException(x); } } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1282"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package makeithappen.vaadin.app.internal; import org.eclipse.emf.ecp.makeithappen.model.task.TaskFactory; import org.eclipse.emf.ecp.makeithappen.model.task.User; import org.eclipse.emf.ecp.view.core.vaadin.ECPVaadinView; import org.eclipse.emf.ecp.view.core.vaadin.ECPVaadinViewRenderer; import org.lunifera.runtime.web.vaadin.databinding.VaadinObservables; import com.vaadin.annotations.Push; import com.vaadin.annotations.Theme; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.UI; import com.vaadin.ui.themes.ValoTheme; // @PreserveOnRefresh @Theme(ValoTheme.THEME_NAME) // @Theme(Reindeer.THEME_NAME) @Push /** * Render the eObject. * @author Dennis Melzer * */ public class VaadinMainUI extends UI { private static final long serialVersionUID = 1L; final static User USER = TaskFactory.eINSTANCE.createUser(); @Override protected void init(VaadinRequest request) { getPage().setTitle("Test Vaadin Valo"); VaadinObservables.activateRealm(this); final ECPVaadinView ecpVaadinView = ECPVaadinViewRenderer.INSTANCE.render(USER); setContent(ecpVaadinView.getComponent()); } @Override protected void refresh(VaadinRequest request) { } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1283"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.openhab.binding.heos.internal.discovery; import static org.openhab.binding.heos.HeosBindingConstants.*; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.config.discovery.DiscoveryResult; import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder; import org.eclipse.smarthome.config.discovery.upnp.UpnpDiscoveryParticipant; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.ThingUID; import org.jupnp.model.meta.DeviceDetails; import org.jupnp.model.meta.ManufacturerDetails; import org.jupnp.model.meta.ModelDetails; import org.jupnp.model.meta.RemoteDevice; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link HeosDiscoveryParticipant} discovers the HEOS Player of the * network via an UPnP interface. * * @author Johannes Einig - Initial contribution */ @NonNullByDefault public class HeosDiscoveryParticipant implements UpnpDiscoveryParticipant { private Logger logger = LoggerFactory.getLogger(HeosDiscoveryParticipant.class); @Override public Set<ThingTypeUID> getSupportedThingTypeUIDs() { return Collections.singleton(THING_TYPE_BRIDGE); } @Override public @Nullable DiscoveryResult createResult(RemoteDevice device) { ThingUID uid = getThingUID(device); if (uid != null) { Map<String, Object> properties = new HashMap<>(2); properties.put(HOST, device.getIdentity().getDescriptorURL().getHost()); properties.put(NAME, device.getDetails().getModelDetails().getModelName()); DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties) .withLabel(device.getDetails().getFriendlyName()).withRepresentationProperty(PLAYER_TYPE).build(); logger.info("Found HEOS device with UID: {}", uid.getAsString()); return result; } return null; } @Override public @Nullable ThingUID getThingUID(RemoteDevice device) { Optional<RemoteDevice> optDevice = Optional.ofNullable(device); String modelName = optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getModelDetails) .map(ModelDetails::getModelName).orElse("UNKNOWN"); String modelManufacturer = optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getManufacturerDetails) .map(ManufacturerDetails::getManufacturer).orElse("UNKNOWN"); if (modelManufacturer.equals("Denon")) { if (modelName.startsWith("HEOS") || modelName.endsWith("H")) { if (device.getType().getType().startsWith("ACT")) { return new ThingUID(THING_TYPE_BRIDGE, optDevice.get().getIdentity().getUdn().getIdentifierString()); } } } return null; // optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getModelDetails).map(ModelDetails::getModelName) // .ifPresent(modelName -> { // optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getManufacturerDetails) // .map(ManufacturerDetails::getManufacturer).ifPresent(modelManufacturer -> { // if (modelManufacturer.equals("Denon")) { // if (modelName.startsWith("HEOS") || modelName.endsWith("H")) { // if (device.getType().getType().startsWith("ACT")) { // thingUID = new ThingUID(THING_TYPE_BRIDGE, // optDevice.get().getIdentity().getUdn().getIdentifierString()); // return thingUID; // DeviceDetails details = device.getDetails(); // if (details != null) { // ModelDetails modelDetails = details.getModelDetails(); // ManufacturerDetails modelManufacturerDetails = details.getManufacturerDetails(); // if (modelDetails != null && modelManufacturerDetails != null) { // String modelName = modelDetails.getModelName(); // String modelManufacturer = modelManufacturerDetails.getManufacturer(); // if (modelName != null && modelManufacturer != null) { // if (modelManufacturer.equals("Denon")) { // if (modelName.startsWith("HEOS") || modelName.endsWith("H")) { // if (device.getType().getType().startsWith("ACT")) { // return new ThingUID(THING_TYPE_BRIDGE, // device.getIdentity().getUdn().getIdentifierString()); // return null; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1284"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.eclipse.persistence.exceptions.i18n; import java.text.MessageFormat; import java.util.Locale; import java.util.ResourceBundle; import java.util.Vector; import org.eclipse.persistence.internal.helper.ConversionManager; import org.eclipse.persistence.internal.helper.Helper; public class ExceptionMessageGenerator { /** * Return the loader for loading the resource bundles. */ public static ClassLoader getLoader() { ClassLoader loader = ExceptionMessageGenerator.class.getClassLoader(); if (loader == null) { loader = ConversionManager.getDefaultManager().getLoader(); } return loader; } /** * Return the message for the given exception class and error number. */ public static String buildMessage(Class exceptionClass, int errorNumber, Object[] arguments) { final String CR = System.getProperty("line.separator"); String shortClassName = Helper.getShortClassName(exceptionClass); String message = ""; ResourceBundle bundle = null; // JDK 1.1 MessageFormat can't handle null arguments for (int i = 0; i < arguments.length; i++) { if (arguments[i] == null) { arguments[i] = "null"; } } bundle = ResourceBundle.getBundle("org.eclipse.persistence.exceptions.i18n." + shortClassName + "Resource", Locale.getDefault(), getLoader()); try { message = bundle.getString(String.valueOf(errorNumber)); } catch (java.util.MissingResourceException mre) { // Found bundle, but couldn't find exception translation. // Get the current language's NoExceptionTranslationForThisLocale message. bundle = ResourceBundle.getBundle("org.eclipse.persistence.exceptions.i18n.ExceptionResource", Locale.getDefault(), getLoader()); String noTranslationMessage = bundle.getString("NoExceptionTranslationForThisLocale"); Object[] args = { CR }; return format(message, arguments) + format(noTranslationMessage, args); } return format(message, arguments); } /** * Return the formatted message for the given exception class and error number. */ //Bug#4619864 Catch any exception during formatting and try to throw that exception. One possibility is toString() to an argument protected static String format(String message, Object[] arguments) { try { return MessageFormat.format(message, arguments); } catch (Exception ex) { ResourceBundle bundle = null; bundle = ResourceBundle.getBundle("org.eclipse.persistence.exceptions.i18n.ExceptionResource", Locale.getDefault(), getLoader()); String errorMessage = bundle.getString("ErrorFormattingMessage"); Vector vec = new Vector(); if (arguments != null) { for (int index = 0; index < arguments.length; index++) { try { vec.add(arguments[index].toString()); } catch (Exception ex2) { vec.add(ex2); } } } return MessageFormat.format(errorMessage, new Object[] {message, vec}); } } /** * Get one of the generic headers used for the exception's toString(). * * E.g., "EXCEPTION DESCRIPTION: ", "ERROR CODE: ", etc. */ public static String getHeader(String headerLabel) { ResourceBundle bundle = null; try { bundle = ResourceBundle.getBundle("org.eclipse.persistence.exceptions.i18n.ExceptionResource", Locale.getDefault(), getLoader()); return bundle.getString(headerLabel); } catch (java.util.MissingResourceException mre) { return "[" + headerLabel + "]"; } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1285"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.eclipse.persistence.internal.oxm.record; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.eclipse.persistence.internal.oxm.record.namespaces.UnmarshalNamespaceContext; import org.eclipse.persistence.oxm.XMLConstants; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.ext.LexicalHandler; /** * Convert and XMLStreamReader into SAX events. */ public class XMLStreamReaderReader extends XMLReader { private ContentHandler contentHandler; private LexicalHandler lexicalHandler; private ErrorHandler errorHandler; private int depth = 0; public XMLStreamReaderReader() { } @Override public ContentHandler getContentHandler() { return contentHandler; } @Override public void setContentHandler(ContentHandler aContentHandler) { this.contentHandler = aContentHandler; } @Override public ErrorHandler getErrorHandler() { return errorHandler; } @Override public void setErrorHandler(ErrorHandler anErrorHandler) { this.errorHandler = anErrorHandler; } @Override public void setProperty (String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { if(name.equals("http://xml.org/sax/properties/lexical-handler")) { lexicalHandler = (LexicalHandler)value; } } @Override public void parse(InputSource input) throws SAXException { if(input instanceof XMLStreamReaderInputSource) { XMLStreamReader xmlStreamReader = ((XMLStreamReaderInputSource) input).getXmlStreamReader(); parse(xmlStreamReader); } } @Override public void parse(InputSource input, SAXUnmarshallerHandler saxUnmarshallerHandler) throws SAXException { if(input instanceof XMLStreamReaderInputSource) { XMLStreamReader xmlStreamReader = ((XMLStreamReaderInputSource) input).getXmlStreamReader(); saxUnmarshallerHandler.setUnmarshalNamespaceResolver(new UnmarshalNamespaceContext(xmlStreamReader)); parse(xmlStreamReader); } } public void parse(String systemId) throws SAXException {} private void parse(XMLStreamReader xmlStreamReader) throws SAXException { try{ parseEvent(xmlStreamReader); while(depth > 0 && xmlStreamReader.hasNext()) { xmlStreamReader.next(); parseEvent(xmlStreamReader); } }catch(XMLStreamException e) { throw new RuntimeException(e); } } private void parseEvent(XMLStreamReader xmlStreamReader) throws SAXException { if(null == getContentHandler()) { return; } switch (xmlStreamReader.getEventType()) { case XMLStreamReader.ATTRIBUTE: { break; } case XMLStreamReader.CDATA: { if(null == lexicalHandler) { getContentHandler().characters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength()); } else { lexicalHandler.startCDATA(); getContentHandler().characters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength()); lexicalHandler.endCDATA(); } break; } case XMLStreamReader.CHARACTERS: { getContentHandler().characters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength()); break; } case XMLStreamReader.COMMENT: { if(null != lexicalHandler) { lexicalHandler.comment(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength()); } break; } case XMLStreamReader.DTD: { break; } case XMLStreamReader.END_DOCUMENT: { depth getContentHandler().endDocument(); return; } case XMLStreamReader.END_ELEMENT: { depth String prefix = xmlStreamReader.getPrefix(); if(null == prefix || prefix.length() == 0) { getContentHandler().endElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), xmlStreamReader.getLocalName()); } else { getContentHandler().endElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), prefix + XMLConstants.COLON + xmlStreamReader.getLocalName()); } break; } case XMLStreamReader.ENTITY_DECLARATION: { break; } case XMLStreamReader.ENTITY_REFERENCE: { break; } case XMLStreamReader.NAMESPACE: { break; } case XMLStreamReader.NOTATION_DECLARATION: { break; } case XMLStreamReader.PROCESSING_INSTRUCTION: { getContentHandler().processingInstruction(xmlStreamReader.getPITarget(), xmlStreamReader.getPIData()); break; } case XMLStreamReader.SPACE: { char[] characters = xmlStreamReader.getTextCharacters(); getContentHandler().characters(characters, 0, characters.length); break; } case XMLStreamReader.START_DOCUMENT: { depth++; getContentHandler().startDocument(); break; } case XMLStreamReader.START_ELEMENT: { depth++; String prefix = xmlStreamReader.getPrefix(); if(null == prefix || prefix.length() == 0) { getContentHandler().startElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), xmlStreamReader.getLocalName(), new IndexedAttributeList(xmlStreamReader)); } else { getContentHandler().startElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), prefix + XMLConstants.COLON + xmlStreamReader.getLocalName(), new IndexedAttributeList(xmlStreamReader)); } break; } } } private static class IndexedAttributeList implements Attributes { private List<Attribute> attributes; public IndexedAttributeList(XMLStreamReader xmlStreamReader) { int namespaceCount = xmlStreamReader.getNamespaceCount(); int attributeCount = xmlStreamReader.getAttributeCount(); attributes = new ArrayList<Attribute>(attributeCount + namespaceCount); for(int x=0; x<namespaceCount; x++) { String uri = XMLConstants.XMLNS_URL; String localName = xmlStreamReader.getNamespacePrefix(x); String qName; if(null == localName || localName.length() == 0) { localName = XMLConstants.XMLNS; qName = XMLConstants.XMLNS; } else { qName = XMLConstants.XMLNS + XMLConstants.COLON + localName; } String value = xmlStreamReader.getNamespaceURI(x); attributes.add(new Attribute(uri, localName, qName, value)); } for(int x=0; x<attributeCount; x++) { String uri = xmlStreamReader.getAttributeNamespace(x); String localName = xmlStreamReader.getAttributeLocalName(x); String prefix = xmlStreamReader.getAttributePrefix(x); String qName; if(null == prefix || prefix.length() == 0) { qName = localName; } else { qName = prefix + XMLConstants.COLON + localName; } String value = xmlStreamReader.getAttributeValue(x); attributes.add(new Attribute(uri, localName, qName, value)); } } public int getIndex(String qName) { if(null == qName) { return -1; } int index = 0; for(Attribute attribute : attributes) { if(qName.equals(attribute.getName())) { return index; } index++; } return -1; } public int getIndex(String uri, String localName) { if(null == localName) { return -1; } int index = 0; for(Attribute attribute : attributes) { QName testQName = new QName(uri, localName); if(attribute.getQName().equals(testQName)) { return index; } index++; } return -1; } public int getLength() { return attributes.size(); } public String getLocalName(int index) { return attributes.get(index).getQName().getLocalPart(); } public String getQName(int index) { return attributes.get(index).getName(); } public String getType(int index) { return XMLConstants.CDATA; } public String getType(String name) { return XMLConstants.CDATA; } public String getType(String uri, String localName) { return XMLConstants.CDATA; } public String getURI(int index) { return attributes.get(index).getQName().getNamespaceURI(); } public String getValue(int index) { return attributes.get(index).getValue(); } public String getValue(String qName) { int index = getIndex(qName); if(-1 == index) { return null; } return attributes.get(index).getValue(); } public String getValue(String uri, String localName) { int index = getIndex(uri, localName); if(-1 == index) { return null; } return attributes.get(index).getValue(); } } private static class Attribute { private QName qName; private String name; private String value; public Attribute(String uri, String localName, String name, String value) { this.qName = new QName(uri, localName); this.name = name; this.value = value; } public QName getQName() { return qName; } public String getName() { return name; } public String getValue() { return value; } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1286"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package net.java.sip.communicator.impl.protocol.yahoo; import java.io.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; import ymsg.network.*; import ymsg.network.event.*; /** * An implementation of the protocol provider service over the Yahoo protocol * * @author Damian Minkov */ public class ProtocolProviderServiceYahooImpl extends AbstractProtocolProviderService { private static final Logger logger = Logger.getLogger(ProtocolProviderServiceYahooImpl.class); private YahooSession yahooSession = null; /** * indicates whether or not the provider is initialized and ready for use. */ private boolean isInitialized = false; /** * We use this to lock access to initialization. */ private final Object initializationLock = new Object(); /** * The identifier of the account that this provider represents. */ private AccountID accountID = null; /** * Used when we need to re-register */ private SecurityAuthority authority = null; private OperationSetPersistentPresenceYahooImpl persistentPresence = null; private OperationSetTypingNotificationsYahooImpl typingNotifications = null; /** * The logo corresponding to the msn protocol. */ private ProtocolIconYahooImpl yahooIcon = new ProtocolIconYahooImpl(); /** * Returns the state of the registration of this protocol provider * @return the <tt>RegistrationState</tt> that this provider is * currently in or null in case it is in a unknown state. */ public RegistrationState getRegistrationState() { if(yahooSession != null && yahooSession.getSessionStatus() == StatusConstants.MESSAGING) return RegistrationState.REGISTERED; else return RegistrationState.UNREGISTERED; } /** * Starts the registration process. Connection details such as * registration server, user name/number are provided through the * configuration service through implementation specific properties. * * @param authority the security authority that will be used for resolving * any security challenges that may be returned during the * registration or at any moment while wer're registered. * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void register(final SecurityAuthority authority) throws OperationFailedException { if(authority == null) throw new IllegalArgumentException( "The register method needs a valid non-null authority impl " + " in order to be able and retrieve passwords."); this.authority = authority; connectAndLogin(authority, SecurityAuthority.AUTHENTICATION_REQUIRED); } /** * Connects and logins to the server * @param authority SecurityAuthority * @param authReasonCode the authentication reason code, which should * indicate why are making an authentication request * @throws XMPPException if we cannot connect to the server - network problem * @throws OperationFailedException if login parameters * as server port are not correct */ private void connectAndLogin( SecurityAuthority authority, int authReasonCode) throws OperationFailedException { synchronized(initializationLock) { //verify whether a password has already been stored for this account String password = YahooActivator. getProtocolProviderFactory().loadPassword(getAccountID()); //decode if (password == null) { //create a default credentials object UserCredentials credentials = new UserCredentials(); credentials.setUserName(getAccountID().getUserID()); //request a password from the user credentials = authority.obtainCredentials( ProtocolNames.YAHOO, credentials, authReasonCode); //extract the password the user passed us. char[] pass = credentials.getPassword(); // the user didn't provide us a password (canceled the operation) if(pass == null) { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.UNREGISTERED, RegistrationStateChangeEvent.REASON_USER_REQUEST, ""); return; } password = new String(pass); if (credentials.isPasswordPersistent()) { YahooActivator.getProtocolProviderFactory() .storePassword(getAccountID(), password); } } yahooSession = new YahooSession(); yahooSession.addSessionListener(new YahooConnectionListener()); try { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.REGISTERING, RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null); yahooSession.login(getAccountID().getUserID(), password); if(yahooSession.getSessionStatus()==StatusConstants.MESSAGING) { persistentPresence.fireProviderStatusChangeEvent( persistentPresence.getPresenceStatus(), persistentPresence.yahooStatusToPresenceStatus( yahooSession.getStatus())); fireRegistrationStateChanged( getRegistrationState(), RegistrationState.REGISTERED, RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null); } else { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.UNREGISTERED, RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null); } } catch (LoginRefusedException ex) { if(ex.getStatus() == StatusConstants.STATUS_BADUSERNAME) { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.AUTHENTICATION_FAILED, RegistrationStateChangeEvent.REASON_NON_EXISTING_USER_ID, null); reregister(SecurityAuthority.WRONG_USERNAME); } else if(ex.getStatus() == StatusConstants.STATUS_BAD) { YahooActivator.getProtocolProviderFactory() .storePassword(getAccountID(), null); fireRegistrationStateChanged( getRegistrationState(), RegistrationState.AUTHENTICATION_FAILED, RegistrationStateChangeEvent.REASON_AUTHENTICATION_FAILED, null); // Try to re-register and ask the user to retype the password. reregister(SecurityAuthority.WRONG_PASSWORD); } else if(ex.getStatus() == StatusConstants.STATUS_LOCKED) { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.AUTHENTICATION_FAILED, RegistrationStateChangeEvent.REASON_RECONNECTION_RATE_LIMIT_EXCEEDED, null); } } catch (IOException ex) { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.CONNECTION_FAILED, RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null); } } } /** * Reconnects if fails fire connection failed. * @param reasonCode the appropriate <tt>SecurityAuthority</tt> reasonCode, * which would specify the reason for which we're re-calling the login. */ void reregister(int reasonCode) { try { connectAndLogin(authority, reasonCode); } catch (OperationFailedException ex) { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.CONNECTION_FAILED, RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null); } } /** * Ends the registration of this protocol provider with the service. */ public void unregister() { unregister(true); } /** * Unregister and fire the event if requested * @param fireEvent boolean */ void unregister(boolean fireEvent) { RegistrationState currRegState = getRegistrationState(); try { if((yahooSession != null) && (yahooSession.getSessionStatus() == StatusConstants.MESSAGING)) yahooSession.logout(); } catch(Exception ex) { logger.error("Cannot logout! ", ex); } yahooSession = null; if(fireEvent) fireRegistrationStateChanged( currRegState, RegistrationState.UNREGISTERED, RegistrationStateChangeEvent.REASON_USER_REQUEST, null); } /** * Returns the short name of the protocol that the implementation of this * provider is based upon (like SIP, Msn, ICQ/AIM, or others for * example). * * @return a String containing the short name of the protocol this * service is taking care of. */ public String getProtocolName() { return ProtocolNames.YAHOO; } /** * Initialized the service implementation, and puts it in a sate where it * could interoperate with other services. It is strongly recomended that * properties in this Map be mapped to property names as specified by * <tt>AccountProperties</tt>. * * @param screenname the account id/uin/screenname of the account that * we're about to create * @param accountID the identifier of the account that this protocol * provider represents. * * @see net.java.sip.communicator.service.protocol.AccountID */ protected void initialize(String screenname, AccountID accountID) { synchronized(initializationLock) { this.accountID = accountID; addSupportedOperationSet( OperationSetInstantMessageTransform.class, new OperationSetInstantMessageTransformImpl()); //initialize the presence operationset persistentPresence = new OperationSetPersistentPresenceYahooImpl(this); addSupportedOperationSet( OperationSetPersistentPresence.class, persistentPresence); //register it once again for those that simply need presence addSupportedOperationSet( OperationSetPresence.class, persistentPresence); //initialize the IM operation set addSupportedOperationSet( OperationSetBasicInstantMessaging.class, new OperationSetBasicInstantMessagingYahooImpl(this)); //initialize the multi user chat operation set addSupportedOperationSet( OperationSetAdHocMultiUserChat.class, new OperationSetAdHocMultiUserChatYahooImpl(this)); //initialize the typing notifications operation set typingNotifications = new OperationSetTypingNotificationsYahooImpl(this); addSupportedOperationSet( OperationSetTypingNotifications.class, typingNotifications); addSupportedOperationSet( OperationSetFileTransfer.class, new OperationSetFileTransferYahooImpl(this)); isInitialized = true; } } /** * Makes the service implementation close all open sockets and release * any resources that it might have taken and prepare for * shutdown/garbage collection. */ public void shutdown() { synchronized(initializationLock){ unregister(false); yahooSession = null; isInitialized = false; } } /** * Returns true if the provider service implementation is initialized and * ready for use by other services, and false otherwise. * * @return true if the provider is initialized and ready for use and false * otherwise */ public boolean isInitialized() { return isInitialized; } /** * Returns the AccountID that uniquely identifies the account represented * by this instance of the ProtocolProviderService. * @return the id of the account represented by this provider. */ public AccountID getAccountID() { return accountID; } /** * Returns the Yahoo<tt>Session</tt>opened by this provider * @return a reference to the <tt>Session</tt> last opened by this * provider. */ YahooSession getYahooSession() { return yahooSession; } /** * Creates a RegistrationStateChange event corresponding to the specified * old and new states and notifies all currently registered listeners. * * @param oldState the state that the provider had before the change * occurred * @param newState the state that the provider is currently in. * @param reasonCode a value corresponding to one of the REASON_XXX fields * of the RegistrationStateChangeEvent class, indicating the reason for * this state transition. * @param reason a String further explaining the reason code or null if * no such explanation is necessary. */ public void fireRegistrationStateChanged( RegistrationState oldState, RegistrationState newState, int reasonCode, String reason) { if(newState.equals(RegistrationState.UNREGISTERED) || newState.equals(RegistrationState.CONNECTION_FAILED)) { unregister(false); yahooSession = null; } super.fireRegistrationStateChanged(oldState, newState, reasonCode, reason); } /** * Listens when we are logged in the server * or incoming exception in the lib impl. */ private class YahooConnectionListener extends SessionAdapter { /** * Yahoo has logged us off the system, or the connection was lost **/ public void connectionClosed(SessionEvent ev) { unregister(true); if(isRegistered()) fireRegistrationStateChanged( getRegistrationState(), RegistrationState.CONNECTION_FAILED, RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null); } public void inputExceptionThrown(SessionExceptionEvent ev) { if(ev.getException() instanceof YMSG9BadFormatException) { logger.error("Yahoo protocol exception occured exception", ev.getException()); logger.error("Yahoo protocol exception occured exception cause", ev.getException().getCause()); } else logger.error( "Yahoo protocol exception occured", ev.getException()); unregister(false); if(isRegistered()) fireRegistrationStateChanged( getRegistrationState(), RegistrationState.UNREGISTERED, RegistrationStateChangeEvent.REASON_INTERNAL_ERROR, null); } } /** * Returns the yahoo protocol icon. * @return the yahoo protocol icon */ public ProtocolIcon getProtocolIcon() { return yahooIcon; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1287"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package gobblin.ingestion.google.adwords; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingDeque; import java.util.zip.GZIPInputStream; import org.apache.commons.lang3.tuple.Pair; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import com.google.api.ads.adwords.lib.client.AdWordsSession; import com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration; import com.google.api.ads.adwords.lib.jaxb.v201609.DateRange; import com.google.api.ads.adwords.lib.jaxb.v201609.DownloadFormat; import com.google.api.ads.adwords.lib.jaxb.v201609.ReportDefinition; import com.google.api.ads.adwords.lib.jaxb.v201609.ReportDefinitionDateRangeType; import com.google.api.ads.adwords.lib.jaxb.v201609.ReportDefinitionReportType; import com.google.api.ads.adwords.lib.jaxb.v201609.Selector; import com.google.api.ads.adwords.lib.utils.ReportDownloadResponse; import com.google.api.ads.adwords.lib.utils.ReportDownloadResponseException; import com.google.api.ads.adwords.lib.utils.ReportException; import com.google.api.ads.adwords.lib.utils.v201609.ReportDownloader; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.client.util.BackOff; import com.google.api.client.util.ExponentialBackOff; import com.google.gson.JsonArray; import com.google.gson.JsonParser; import com.opencsv.CSVParser; import lombok.extern.slf4j.Slf4j; import gobblin.configuration.WorkUnitState; import gobblin.source.extractor.extract.LongWatermark; @Slf4j public class GoogleAdWordsReportDownloader { private final static CSVParser splitter = new CSVParser(',', '"', '\\'); private final static int SIZE = 4096; //Buffer size for unzipping stream. private final boolean _skipReportHeader; private final boolean _skipColumnHeader; private final boolean _skipReportSummary; private final boolean _includeZeroImpressions; private final boolean _useRawEnumValues; private final AdWordsSession _rootSession; private final ExponentialBackOff.Builder backOffBuilder = new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(1000 * 60 * 5); private final List<String> _columnNames; private final ReportDefinitionReportType _reportType; private final ReportDefinitionDateRangeType _dateRangeType; private final String _startDate; private final String _endDate; private final boolean _dailyPartition; private final static DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyyMMdd"); private final static DateTimeFormatter watermarkFormatter = DateTimeFormat.forPattern("yyyyMMddHHmmss"); /** * debug in FILE mode is to download reports in file format directly */ private final String _debugFileOutputPath; /** * debug in STRING mode is to download reports in strings, then concate and convert all strings to files. */ private final String _debugStringOutputPath; public GoogleAdWordsReportDownloader(AdWordsSession rootSession, WorkUnitState state, ReportDefinitionReportType reportType, ReportDefinitionDateRangeType dateRangeType, String schema) { _rootSession = rootSession; _reportType = reportType; _dateRangeType = dateRangeType; _columnNames = schemaToColumnNames(schema); log.info("Downloaded fields are: " + Arrays.toString(_columnNames.toArray())); long lowWatermark = state.getWorkunit().getLowWatermark(LongWatermark.class).getValue(); _startDate = dateFormatter.print(watermarkFormatter.parseDateTime(Long.toString(lowWatermark))); _endDate = _startDate; _dailyPartition = state.getPropAsBoolean(GoogleAdWordsSource.KEY_CUSTOM_DATE_DAILY, false); _debugFileOutputPath = state.getProp(GoogleAdWordsSource.KEY_DEBUG_PATH_FILE, ""); _debugStringOutputPath = state.getProp(GoogleAdWordsSource.KEY_DEBUG_PATH_STRING, ""); _skipReportHeader = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_SKIP_REPORT_HEADER, true); _skipColumnHeader = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_SKIP_COLUMN_HEADER, true); _skipReportSummary = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_SKIP_REPORT_SUMMARY, true); _useRawEnumValues = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_USE_RAW_ENUM_VALUES, false); _includeZeroImpressions = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_INCLUDE_ZERO_IMPRESSION, false); } static List<String> schemaToColumnNames(String schemaString) { JsonArray schemaArray = new JsonParser().parse(schemaString).getAsJsonArray(); List<String> fields = new ArrayList<>(); for (int i = 0; i < schemaArray.size(); i++) { fields.add(schemaArray.get(i).getAsJsonObject().get("columnName").getAsString()); } return fields; } public void downloadAllReports(Collection<String> accounts, final LinkedBlockingDeque<String[]> reportRows) throws InterruptedException { ExecutorService threadPool = Executors.newFixedThreadPool(Math.min(8, accounts.size())); List<Pair<String, String>> dates = getDates(); Map<String, Future<Void>> jobs = new HashMap<>(); for (String acc : accounts) { final String account = acc; for (Pair<String, String> dateRange : dates) { final Pair<String, String> range = dateRange; final String jobName; if (_dateRangeType.equals(ReportDefinitionDateRangeType.ALL_TIME)) { jobName = String.format("'all-time report for %s'", account); } else { jobName = String.format("'report for %s from %s to %s'", account, range.getLeft(), range.getRight()); } Future<Void> job = threadPool.submit(new Callable<Void>() { @Override public Void call() throws ReportDownloadResponseException, InterruptedException, IOException, ReportException { log.info("Start downloading " + jobName); ExponentialBackOff backOff = backOffBuilder.build(); int numberOfAttempts = 0; while (true) { ++numberOfAttempts; try { downloadReport(account, range.getLeft(), range.getRight(), reportRows); log.info("Successfully downloaded " + jobName); return null; } catch (ReportException e) { long sleepMillis = backOff.nextBackOffMillis(); log.info("Downloading %s failed #%d try: %s. Will sleep for %d milliseconds.", jobName, numberOfAttempts, e.getMessage(), sleepMillis); if (sleepMillis == BackOff.STOP) { throw new ReportException(String .format("Downloading %s failed after maximum elapsed millis: %d", jobName, backOff.getMaxElapsedTimeMillis()), e); } Thread.sleep(sleepMillis); } } } }); jobs.put(jobName, job); Thread.sleep(100); } } threadPool.shutdown(); //Collect all failed jobs. Map<String, Exception> failedJobs = new HashMap<>(); for (Map.Entry<String, Future<Void>> job : jobs.entrySet()) { try { job.getValue().get(); } catch (Exception e) { failedJobs.put(job.getKey(), e); } } if (!failedJobs.isEmpty()) { log.error(String.format("%d downloading jobs failed: ", failedJobs.size())); for (Map.Entry<String, Exception> fail : failedJobs.entrySet()) { log.error(String.format("%s => %s", fail.getKey(), fail.getValue().getMessage())); } } log.info("End of downloading all reports."); } /** * @param account the account of the report you want to download * @param startDate start date for custom_date range type * @param endDate end date for custom_date range type * @param reportRows the sink that accumulates all downloaded rows * @throws ReportDownloadResponseException This is not retryable * @throws ReportException ReportException represents a potentially retryable error */ private void downloadReport(String account, String startDate, String endDate, LinkedBlockingDeque<String[]> reportRows) throws ReportDownloadResponseException, ReportException, InterruptedException, IOException { Selector selector = new Selector(); selector.getFields().addAll(_columnNames); String reportName; if (_dateRangeType.equals(ReportDefinitionDateRangeType.CUSTOM_DATE)) { DateRange value = new DateRange(); value.setMin(startDate); value.setMax(endDate); selector.setDateRange(value); reportName = String.format("%s_%s/%s_%s.csv", startDate, endDate, _reportType.toString(), account); } else { reportName = String.format("all_time/%s_%s.csv", _reportType.toString(), account); } ReportDefinition reportDef = new ReportDefinition(); reportDef.setReportName(reportName); reportDef.setDateRangeType(_dateRangeType); reportDef.setReportType(_reportType); reportDef.setDownloadFormat(DownloadFormat.GZIPPED_CSV); reportDef.setSelector(selector); //API defaults all configurations to false ReportingConfiguration reportConfig = new ReportingConfiguration.Builder().skipReportHeader(_skipReportHeader).skipColumnHeader(_skipColumnHeader) .skipReportSummary(_skipReportSummary) .useRawEnumValues(_useRawEnumValues) //return enum field values as enum values instead of display values .includeZeroImpressions(_includeZeroImpressions).build(); AdWordsSession.ImmutableAdWordsSession session; try { session = _rootSession.newBuilder().withClientCustomerId(account).withReportingConfiguration(reportConfig) .buildImmutable(); } catch (ValidationException e) { throw new RuntimeException(e); } ReportDownloader downloader = new ReportDownloader(session); ReportDownloadResponse response = downloader.downloadReport(reportDef); InputStream zippedStream = response.getInputStream(); if (zippedStream == null) { log.warn("Got empty stream for " + reportName); return; } if (!_debugFileOutputPath.trim().isEmpty()) { //FILE mode debug will not save output to GOBBLIN_WORK_DIR File debugFile = new File(_debugFileOutputPath, reportName); createPath(debugFile); writeZippedStreamToFile(zippedStream, debugFile); return; } FileWriter debugFileWriter = null; try { if (!_debugStringOutputPath.trim().isEmpty()) { //if STRING mode debug is enabled. A copy of downloaded strings/reports will be saved. File debugFile = new File(_debugStringOutputPath, reportName); createPath(debugFile); debugFileWriter = new FileWriter(debugFile); } processResponse(zippedStream, reportRows, debugFileWriter); } catch (IOException e) { throw new RuntimeException( String.format("Failed unzipping and processing records for %s. Reason is: %s", reportName, e.getMessage()), e); } finally { if (debugFileWriter != null) { debugFileWriter.close(); } } } private static void createPath(File file) { //Clean up file if exists if (file.exists()) { boolean delete = file.delete(); if (!delete) { throw new RuntimeException(String.format("Cannot delete debug file: %s", file)); } } boolean created = new File(file.getParent()).mkdirs(); if (!created) { throw new RuntimeException(String.format("Cannot create debug file: %s", file)); } } private static GZIPInputStream processResponse(InputStream zippedStream, LinkedBlockingDeque<String[]> reportRows, FileWriter debugFw) throws IOException, InterruptedException { byte[] buffer = new byte[SIZE]; try (GZIPInputStream gzipInputStream = new GZIPInputStream(zippedStream)) { String partiallyConsumed = ""; while (true) { int c = gzipInputStream.read(buffer, 0, SIZE); if (c == -1) { break; //end of stream } if (c == 0) { continue; //read empty, continue reading } String str = new String(buffer, 0, c, "UTF-8"); //"c" can very likely be less than SIZE. if (debugFw != null) { debugFw.write(str); //save a copy if STRING mode debug is enabled } partiallyConsumed = addToQueue(reportRows, partiallyConsumed, str); } return gzipInputStream; } } /** * Concatenate previously partially consumed string with current read, then try to split the whole string. * A whole record will be added to reportRows(data sink). * The last partially consumed string, if exists, will be returned to be processed in next round. */ static String addToQueue(LinkedBlockingDeque<String[]> reportRows, String previous, String current) throws InterruptedException, IOException { int start = -1; int i = -1; int len = current.length(); while (++i < len) { if (current.charAt(i) != '\n') { continue; } String row; if (start < 0) { row = previous + current.substring(0, i); } else { row = current.substring(start, i); } String[] splits = splitter.parseLine(row); String[] transformed = new String[splits.length]; for (int s = 0; s < splits.length; ++s) { String trimmed = splits[s].trim(); if (trimmed.equals(" transformed[s] = null; } else { transformed[s] = trimmed; } } reportRows.put(transformed); start = i + 1; } if (start < 0) { return previous + current; } return current.substring(start); } private void writeZippedStreamToFile(InputStream zippedStream, File reportFile) throws IOException { byte[] buffer = new byte[SIZE]; int c; try (GZIPInputStream gzipInputStream = new GZIPInputStream(zippedStream); OutputStream unzipped = new FileOutputStream(reportFile)) { while ((c = gzipInputStream.read(buffer, 0, SIZE)) >= 0) { unzipped.write(buffer, 0, c); } } } public List<Pair<String, String>> getDates() { if (_dateRangeType.equals(ReportDefinitionDateRangeType.ALL_TIME)) { return Arrays.asList(Pair.of("", "")); } else { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyyMMdd"); if (_dailyPartition) { DateTime start = dateFormatter.parseDateTime(_startDate); DateTime end = dateFormatter.parseDateTime(_endDate); List<Pair<String, String>> ret = new ArrayList<>(); while (start.compareTo(end) <= 0) { ret.add(Pair.of(dateFormatter.print(start), dateFormatter.print(start))); start = start.plusDays(1); } return ret; } else { return Arrays.asList(Pair.of(_startDate, _endDate)); } } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1288"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.dbflute.erflute.editor.model.diagram_contents.element.node.table; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.dbflute.erflute.core.util.Format; import org.dbflute.erflute.db.DBManager; import org.dbflute.erflute.db.DBManagerFactory; import org.dbflute.erflute.editor.model.ObjectModel; import org.dbflute.erflute.editor.model.diagram_contents.element.connection.Relationship; import org.dbflute.erflute.editor.model.diagram_contents.element.connection.WalkerConnection; import org.dbflute.erflute.editor.model.diagram_contents.element.node.DiagramWalker; import org.dbflute.erflute.editor.model.diagram_contents.element.node.Location; import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.ColumnHolder; import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.CopyColumn; import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.ERColumn; import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.NormalColumn; import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.properties.TableViewProperties; import org.dbflute.erflute.editor.model.diagram_contents.not_element.dictionary.CopyWord; import org.dbflute.erflute.editor.model.diagram_contents.not_element.dictionary.Dictionary; import org.dbflute.erflute.editor.model.diagram_contents.not_element.dictionary.Word; import org.dbflute.erflute.editor.model.diagram_contents.not_element.group.ColumnGroup; public abstract class TableView extends DiagramWalker implements ObjectModel, ColumnHolder, Comparable<TableView> { // Definition private static final long serialVersionUID = 1L; public static final String PROPERTY_CHANGE_PHYSICAL_NAME = "table_view_physicalName"; public static final String PROPERTY_CHANGE_LOGICAL_NAME = "table_view_logicalName"; public static final String PROPERTY_CHANGE_COLUMNS = "columns"; public static final int DEFAULT_WIDTH = 120; public static final int DEFAULT_HEIGHT = 75; public static final Comparator<TableView> PHYSICAL_NAME_COMPARATOR = new TableViewPhysicalNameComparator(); public static final Comparator<TableView> LOGICAL_NAME_COMPARATOR = new TableViewLogicalNameComparator(); // Attribute private String physicalName; private String logicalName; private String description; protected List<ERColumn> columns; protected TableViewProperties tableViewProperties; // Constructor public TableView() { this.columns = new ArrayList<>(); } // Location @Override public void setLocation(Location location) { super.setLocation(location); if (this.getDiagram() != null) { for (final Relationship relationship : getOutgoingRelationshipList()) { relationship.setParentMove(); } for (final Relationship relation : getIncomingRelationshipList()) { relation.setParentMove(); } } } // Column public List<NormalColumn> getNormalColumns() { final List<NormalColumn> normalColumns = new ArrayList<>(); for (final ERColumn column : columns) { if (column instanceof NormalColumn) { normalColumns.add((NormalColumn) column); } } return normalColumns; } public List<NormalColumn> getExpandedColumns() { final List<NormalColumn> expandedColumns = new ArrayList<>(); for (final ERColumn column : this.getColumns()) { if (column instanceof NormalColumn) { final NormalColumn normalColumn = (NormalColumn) column; expandedColumns.add(normalColumn); } else if (column instanceof ColumnGroup) { final ColumnGroup groupColumn = (ColumnGroup) column; expandedColumns.addAll(groupColumn.getColumns()); } } return expandedColumns; } public void setDirty() { this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null); } public void addColumn(ERColumn column) { this.getColumns().add(column); column.setColumnHolder(this); this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null); } public void addColumn(int index, ERColumn column) { this.getColumns().add(index, column); column.setColumnHolder(this); this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null); } public void removeColumn(ERColumn column) { this.columns.remove(column); this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null); } public NormalColumn findColumnByPhysicalName(String physicalName) { final List<NormalColumn> normalColumns = getNormalColumns(); for (final NormalColumn normalColumn : normalColumns) { if (physicalName.equalsIgnoreCase(normalColumn.getPhysicalName())) { return normalColumn; } } return null; } // Copy public TableView copyTableViewData(TableView to) { to.setDiagram(getDiagram()); to.setPhysicalName(getPhysicalName()); to.setLogicalName(getLogicalName()); to.setDescription(getDescription()); final List<ERColumn> columns = new ArrayList<>(); for (final ERColumn fromColumn : getColumns()) { if (fromColumn instanceof NormalColumn) { final NormalColumn normalColumn = (NormalColumn) fromColumn; final NormalColumn copyColumn = new CopyColumn(normalColumn); if (normalColumn.getWord() != null) { copyColumn.setWord(new CopyWord(normalColumn.getWord())); } columns.add(copyColumn); } else { columns.add(fromColumn); } } to.setColumns(columns); to.setOutgoing(getOutgoings()); to.setIncoming(getIncomings()); return to; } public abstract TableView copyData(); // Restructure public void restructureData(TableView to) { final Dictionary dictionary = this.getDiagram().getDiagramContents().getDictionary(); to.setPhysicalName(this.getPhysicalName()); to.setLogicalName(this.getLogicalName()); to.setDescription(this.getDescription()); if (getColor() != null) { to.setColor(this.getColor()[0], this.getColor()[1], this.getColor()[2]); } for (final NormalColumn toColumn : to.getNormalColumns()) { dictionary.remove(toColumn); } final List<ERColumn> columns = new ArrayList<>(); final List<NormalColumn> newPrimaryKeyColumns = new ArrayList<>(); for (final ERColumn fromColumn : getColumns()) { if (columns.stream().anyMatch(c -> c.same(fromColumn))) { continue; } if (fromColumn instanceof NormalColumn) { final CopyColumn copyColumn = (CopyColumn) fromColumn; CopyWord copyWord = copyColumn.getWord(); if (copyColumn.isForeignKey()) { copyWord = null; } if (copyWord != null) { final Word originalWord = copyColumn.getOriginalWord(); dictionary.copyTo(copyWord, originalWord); } final NormalColumn restructuredColumn = copyColumn.getRestructuredColumn(); restructuredColumn.setColumnHolder(this); if (copyWord == null) { restructuredColumn.setWord(null); } columns.add(restructuredColumn); if (restructuredColumn.isPrimaryKey()) { newPrimaryKeyColumns.add(restructuredColumn); } dictionary.add(restructuredColumn); } else { columns.add(fromColumn); } } this.setTargetTableRelation(to, newPrimaryKeyColumns); to.setColumns(columns); } // Relationship private void setTargetTableRelation(TableView sourceTable, List<NormalColumn> newPrimaryKeyColumns) { for (final Relationship relationship : sourceTable.getOutgoingRelationshipList()) { if (relationship.isReferenceForPK()) { final TableView targetTable = relationship.getTargetTableView(); final List<NormalColumn> foreignKeyColumns = relationship.getForeignKeyColumns(); boolean isPrimary = true; boolean isPrimaryChanged = false; for (final NormalColumn primaryKeyColumn : newPrimaryKeyColumns) { boolean isReferenced = false; for (final Iterator<NormalColumn> iter = foreignKeyColumns.iterator(); iter.hasNext();) { final NormalColumn foreignKeyColumn = iter.next(); if (isPrimary) { isPrimary = foreignKeyColumn.isPrimaryKey(); } for (final NormalColumn referencedColumn : foreignKeyColumn.getReferencedColumnList()) { if (referencedColumn == primaryKeyColumn) { isReferenced = true; iter.remove(); break; } } if (isReferenced) { break; } } if (!isReferenced) { if (isPrimary) { isPrimaryChanged = true; } final NormalColumn foreignKeyColumn = new NormalColumn(primaryKeyColumn, primaryKeyColumn, relationship, isPrimary); targetTable.addColumn(foreignKeyColumn); } } for (final NormalColumn removedColumn : foreignKeyColumns) { if (removedColumn.isPrimaryKey()) { isPrimaryChanged = true; } targetTable.removeColumn(removedColumn); } if (isPrimaryChanged) { final List<NormalColumn> nextNewPrimaryKeyColumns = ((ERTable) targetTable).getPrimaryKeys(); this.setTargetTableRelation(targetTable, nextNewPrimaryKeyColumns); } targetTable.setDirty(); } } } public List<Relationship> getIncomingRelationshipList() { final List<Relationship> relations = new ArrayList<>(); for (final WalkerConnection connection : getIncomings()) { if (connection instanceof Relationship) { relations.add((Relationship) connection); } } return relations; } public List<Relationship> getOutgoingRelationshipList() { final List<Relationship> relations = new ArrayList<>(); for (final WalkerConnection connection : getOutgoings()) { if (connection instanceof Relationship) { relations.add((Relationship) connection); } } Collections.sort(relations); return relations; } // Column Group public void replaceColumnGroup(ColumnGroup oldColumnGroup, ColumnGroup newColumnGroup) { final int index = this.columns.indexOf(oldColumnGroup); if (index != -1) { this.columns.remove(index); this.columns.add(index, newColumnGroup); } } // Name with Schema public String getNameWithSchema(String database) { final StringBuilder sb = new StringBuilder(); final DBManager dbManager = DBManagerFactory.getDBManager(database); if (!dbManager.isSupported(DBManager.SUPPORT_SCHEMA)) { return Format.null2blank(this.getPhysicalName()); } final TableViewProperties tableViewProperties = this.getDiagram().getDiagramContents().getSettings().getTableViewProperties(); String schema = this.tableViewProperties.getSchema(); if (schema == null || schema.equals("")) { schema = tableViewProperties.getSchema(); } if (schema != null && !schema.equals("")) { sb.append(schema); sb.append("."); } sb.append(this.getPhysicalName()); return sb.toString(); } // TableView ID public String buildTableViewId() { return getIdPrefix() + "." + getPhysicalName(); } protected abstract String getIdPrefix(); // Basic Override @Override public int compareTo(TableView other) { return PHYSICAL_NAME_COMPARATOR.compare(this, other); } private static class TableViewPhysicalNameComparator implements Comparator<TableView> { @Override public int compare(TableView o1, TableView o2) { if (o1 == o2) { return 0; } if (o2 == null) { return -1; } if (o1 == null) { return 1; } final String schema1 = o1.getTableViewProperties().getSchema(); final String schema2 = o2.getTableViewProperties().getSchema(); final int compareTo = Format.null2blank(schema1).toUpperCase().compareTo(Format.null2blank(schema2).toUpperCase()); if (compareTo != 0) { return compareTo; } int value = Format.null2blank(o1.physicalName).toUpperCase().compareTo(Format.null2blank(o2.physicalName).toUpperCase()); if (value != 0) { return value; } value = Format.null2blank(o1.logicalName).toUpperCase().compareTo(Format.null2blank(o2.logicalName).toUpperCase()); if (value != 0) { return value; } return 0; } } private static class TableViewLogicalNameComparator implements Comparator<TableView> { @Override public int compare(TableView o1, TableView o2) { if (o1 == o2) { return 0; } if (o2 == null) { return -1; } if (o1 == null) { return 1; } final String schema1 = o1.getTableViewProperties().getSchema(); final String schema2 = o2.getTableViewProperties().getSchema(); final int compareTo = Format.null2blank(schema1).toUpperCase().compareTo(Format.null2blank(schema2).toUpperCase()); if (compareTo != 0) { return compareTo; } int value = Format.null2blank(o1.logicalName).toUpperCase().compareTo(Format.null2blank(o2.logicalName).toUpperCase()); if (value != 0) { return value; } value = Format.null2blank(o1.physicalName).toUpperCase().compareTo(Format.null2blank(o2.physicalName).toUpperCase()); if (value != 0) { return value; } return 0; } } @Override public boolean isUsePersistentId() { return false; } @Override public boolean isIndenpendentOnModel() { return false; } // Accessor public String getPhysicalName() { return physicalName; } public void setPhysicalName(String physicalName) { final String old = this.physicalName; this.physicalName = physicalName; this.firePropertyChange(PROPERTY_CHANGE_PHYSICAL_NAME, old, physicalName); } public String getLogicalName() { return logicalName; } public void setLogicalName(String logicalName) { final String old = this.logicalName; this.logicalName = logicalName; this.firePropertyChange(PROPERTY_CHANGE_LOGICAL_NAME, old, logicalName); } @Override public String getName() { return this.getPhysicalName(); // #for_erflute change logical to physical for fixed sort } @Override public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<ERColumn> getColumns() { return columns; } public ERColumn getColumn(int index) { return this.columns.get(index); } public void setColumns(List<ERColumn> columns) { this.columns = columns; for (final ERColumn column : columns) { column.setColumnHolder(this); } firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null); } public TableViewProperties getTableViewProperties() { return tableViewProperties; } public void changeTableViewProperty(final TableView sourceTableView) { sourceTableView.restructureData(this); this.getDiagram().changeTable(sourceTableView); this.getDiagram().doChangeTable(sourceTableView); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1289"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package ca.uhn.fhir.rest.server.interceptor.auth; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.api.AddProfileTagEnum; import ca.uhn.fhir.interceptor.api.HookParams; import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster; import ca.uhn.fhir.interceptor.api.Pointcut; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.rest.annotation.*; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.param.ReferenceParam; import ca.uhn.fhir.rest.param.TokenAndListParam; import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor.ActionRequestDetails; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.rest.server.tenant.UrlBaseTenantIdentificationStrategy; import ca.uhn.fhir.test.utilities.JettyUtil; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.*; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.r4.model.*; import org.junit.*; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.*; public class AuthorizationInterceptorR4Test { private static final String ERR403 = "{\"resourceType\":\"OperationOutcome\",\"issue\":[{\"severity\":\"error\",\"code\":\"processing\",\"diagnostics\":\"Access denied by default policy (no applicable rules)\"}]}"; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(AuthorizationInterceptorR4Test.class); private static CloseableHttpClient ourClient; private static String ourConditionalCreateId; private static FhirContext ourCtx = FhirContext.forR4(); private static boolean ourHitMethod; private static int ourPort; private static List<Resource> ourReturn; private static List<IBaseResource> ourDeleted; private static Server ourServer; private static RestfulServer ourServlet; @Before public void before() { ourCtx.setAddProfileTagWhenEncoding(AddProfileTagEnum.NEVER); ourServlet.getInterceptorService().unregisterAllInterceptors(); ourServlet.setTenantIdentificationStrategy(null); ourReturn = null; ourDeleted = null; ourHitMethod = false; ourConditionalCreateId = "1123"; } private Resource createCarePlan(Integer theId, String theSubjectId) { CarePlan retVal = new CarePlan(); if (theId != null) { retVal.setId(new IdType("CarePlan", (long) theId)); } retVal.setSubject(new Reference("Patient/" + theSubjectId)); return retVal; } private Resource createDiagnosticReport(Integer theId, String theSubjectId) { DiagnosticReport retVal = new DiagnosticReport(); if (theId != null) { retVal.setId(new IdType("DiagnosticReport", (long) theId)); } retVal.getCode().setText("OBS"); retVal.setSubject(new Reference(theSubjectId)); return retVal; } private HttpEntity createFhirResourceEntity(IBaseResource theResource) { String out = ourCtx.newJsonParser().encodeResourceToString(theResource); return new StringEntity(out, ContentType.create(Constants.CT_FHIR_JSON, "UTF-8")); } private Resource createObservation(Integer theId, String theSubjectId) { Observation retVal = new Observation(); if (theId != null) { retVal.setId(new IdType("Observation", (long) theId)); } retVal.getCode().setText("OBS"); retVal.setSubject(new Reference(theSubjectId)); if (theSubjectId != null && theSubjectId.startsWith(" Patient p = new Patient(); p.setId(theSubjectId); p.setActive(true); retVal.addContained(p); } return retVal; } private Organization createOrganization(int theIndex) { Organization retVal = new Organization(); retVal.setId("" + theIndex); retVal.setName("Org " + theIndex); return retVal; } private Resource createPatient(Integer theId) { Patient retVal = new Patient(); if (theId != null) { retVal.setId(new IdType("Patient", (long) theId)); } retVal.addName().setFamily("FAM"); return retVal; } private Resource createPatient(Integer theId, int theVersion) { Resource retVal = createPatient(theId); retVal.setId(retVal.getIdElement().withVersion(Integer.toString(theVersion))); return retVal; } private Bundle createTransactionWithPlaceholdersRequestBundle() { // Create a input that will be used as a transaction Bundle input = new Bundle(); input.setType(Bundle.BundleType.TRANSACTION); String encounterId = "123-123"; String encounterSystem = "http://our.internal.code.system/encounter"; Encounter encounter = new Encounter(); encounter.addIdentifier(new Identifier().setValue(encounterId) .setSystem(encounterSystem)); encounter.setStatus(Encounter.EncounterStatus.FINISHED); Patient p = new Patient() .addIdentifier(new Identifier().setValue("321-321").setSystem("http://our.internal.code.system/patient")); p.setId(IdDt.newRandomUuid()); // add patient to input so its created input.addEntry() .setFullUrl(p.getId()) .setResource(p) .getRequest() .setUrl("Patient") .setMethod(Bundle.HTTPVerb.POST); Reference patientRef = new Reference(p.getId()); encounter.setSubject(patientRef); Condition condition = new Condition() .setCode(new CodeableConcept().addCoding( new Coding("http://hl7.org/fhir/icd-10", "S53.40", "FOREARM SPRAIN / STRAIN"))) .setSubject(patientRef); condition.setId(IdDt.newRandomUuid()); // add condition to input so its created input.addEntry() .setFullUrl(condition.getId()) .setResource(condition) .getRequest() .setUrl("Condition") .setMethod(Bundle.HTTPVerb.POST); Encounter.DiagnosisComponent dc = new Encounter.DiagnosisComponent(); dc.setCondition(new Reference(condition.getId())); encounter.addDiagnosis(dc); CodeableConcept reason = new CodeableConcept(); reason.setText("SLIPPED ON FLOOR,PAIN L) ELBOW"); encounter.addReasonCode(reason); // add encounter to input so its created input.addEntry() .setResource(encounter) .getRequest() .setUrl("Encounter") .setIfNoneExist("identifier=" + encounterSystem + "|" + encounterId) .setMethod(Bundle.HTTPVerb.POST); return input; } private Bundle createTransactionWithPlaceholdersResponseBundle() { Bundle output = new Bundle(); output.setType(Bundle.BundleType.TRANSACTIONRESPONSE); output.addEntry() .setResource(new Patient().setActive(true)) // don't give this an ID .getResponse().setLocation("/Patient/1"); return output; } private String extractResponseAndClose(HttpResponse status) throws IOException { if (status.getEntity() == null) { return null; } String responseContent; responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); return responseContent; } @Test public void testAllowAll() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .deny("Rule 1").read().resourcesOfType(Patient.class).withAnyId().andThen() .allowAll("Default Rule") .build(); } }); HttpGet httpGet; HttpResponse status; String response; ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by rule: Rule 1")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$validate"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testAllowAllForTenant() throws Exception { ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy()); ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .deny("Rule 1").read().resourcesOfType(Patient.class).withAnyId().forTenantIds("TENANTA").andThen() .allowAll("Default Rule") .build(); } }); HttpGet httpGet; HttpResponse status; String response; ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Observation/10"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/1"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by rule: Rule 1")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/1/$validate"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testAllowByCompartmentUsingUnqualifiedIds() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder().allow().read().resourcesOfType(CarePlan.class).inCompartment("Patient", new IdType("Patient/123")).andThen().denyAll() .build(); } }); HttpGet httpGet; HttpResponse status; Patient patient; CarePlan carePlan; // Unqualified patient = new Patient(); patient.setId("123"); carePlan = new CarePlan(); carePlan.setStatus(CarePlan.CarePlanStatus.ACTIVE); carePlan.getSubject().setResource(patient); ourHitMethod = false; ourReturn = Collections.singletonList(carePlan); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Qualified patient = new Patient(); patient.setId("Patient/123"); carePlan = new CarePlan(); carePlan.setStatus(CarePlan.CarePlanStatus.ACTIVE); carePlan.getSubject().setResource(patient); ourHitMethod = false; ourReturn = Collections.singletonList(carePlan); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Wrong one patient = new Patient(); patient.setId("456"); carePlan = new CarePlan(); carePlan.setStatus(CarePlan.CarePlanStatus.ACTIVE); carePlan.getSubject().setResource(patient); ourHitMethod = false; ourReturn = Collections.singletonList(carePlan); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } /** * #528 */ @Test public void testAllowByCompartmentWithAnyType() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a")) .andThen().denyAll() .build(); } }); HttpGet httpGet; HttpResponse status; ourHitMethod = false; ourReturn = Collections.singletonList(createCarePlan(10, "845bd9f1-3635-4866-a6c8-1ca085df5c1a")); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createCarePlan(10, "FOO")); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testAllowByCompartmentWithAnyTypeWithTenantId() throws Exception { ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy()); ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a")).forTenantIds("TENANTA") .andThen().denyAll() .build(); } }); HttpGet httpGet; HttpResponse status; ourHitMethod = false; ourReturn = Collections.singletonList(createCarePlan(10, "845bd9f1-3635-4866-a6c8-1ca085df5c1a")); httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createCarePlan(10, "FOO")); httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } /** * #528 */ @Test public void testAllowByCompartmentWithType() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder().allow("Rule 1").read().resourcesOfType(CarePlan.class).inCompartment("Patient", new IdType("Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a")).andThen().denyAll() .build(); } }); HttpGet httpGet; HttpResponse status; ourHitMethod = false; ourReturn = Collections.singletonList(createCarePlan(10, "845bd9f1-3635-4866-a6c8-1ca085df5c1a")); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createCarePlan(10, "FOO")); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testBatchWhenOnlyTransactionAllowed() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").transaction().withAnyOperation().andApplyNormalRules().andThen() .allow("Rule 2").write().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .build(); } }); Bundle input = new Bundle(); input.setType(Bundle.BundleType.BATCH); input.addEntry().setResource(createPatient(1)).getRequest().setUrl("/Patient").setMethod(Bundle.HTTPVerb.POST); Bundle output = new Bundle(); output.setType(Bundle.BundleType.TRANSACTIONRESPONSE); output.addEntry().getResponse().setLocation("/Patient/1"); HttpPost httpPost; HttpResponse status; ourReturn = Collections.singletonList(output); ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(createFhirResourceEntity(input)); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); } @Test public void testBatchWhenTransactionReadDenied() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").transaction().withAnyOperation().andApplyNormalRules().andThen() .allow("Rule 2").write().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .build(); } }); Bundle input = new Bundle(); input.setType(Bundle.BundleType.BATCH); input.addEntry().setResource(createPatient(1)).getRequest().setUrl("/Patient").setMethod(Bundle.HTTPVerb.POST); Bundle output = new Bundle(); output.setType(Bundle.BundleType.TRANSACTIONRESPONSE); output.addEntry().setResource(createPatient(2)); HttpPost httpPost; HttpResponse status; ourReturn = Collections.singletonList(output); ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(createFhirResourceEntity(input)); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); } @Test public void testBatchWhenTransactionWrongBundleType() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").transaction().withAnyOperation().andApplyNormalRules().andThen() .allow("Rule 2").write().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .build(); } }); Bundle input = new Bundle(); input.setType(Bundle.BundleType.COLLECTION); input.addEntry().setResource(createPatient(1)).getRequest().setUrl("/Patient").setMethod(Bundle.HTTPVerb.POST); Bundle output = new Bundle(); output.setType(Bundle.BundleType.TRANSACTIONRESPONSE); output.addEntry().setResource(createPatient(1)); HttpPost httpPost; HttpResponse status; String response; ourReturn = Collections.singletonList(output); ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(createFhirResourceEntity(input)); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(422, status.getStatusLine().getStatusCode()); } @Test public void testDeleteByCompartment() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").delete().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").delete().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }); HttpDelete httpDelete; HttpResponse status; ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient/2"); status = ourClient.execute(httpDelete); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(1)); httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient/1"); status = ourClient.execute(httpDelete); extractResponseAndClose(status); assertEquals(204, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testDeleteByCompartmentUsingTransaction() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").delete().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").delete().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow().transaction().withAnyOperation().andApplyNormalRules().andThen() .build(); } }); HttpPost httpPost; HttpResponse status; String responseString; Bundle responseBundle = new Bundle(); responseBundle.setType(Bundle.BundleType.TRANSACTIONRESPONSE); Bundle bundle = new Bundle(); bundle.setType(Bundle.BundleType.TRANSACTION); ourHitMethod = false; bundle.getEntry().clear(); ourReturn = Collections.singletonList(responseBundle); ourDeleted = Collections.singletonList(createPatient(2)); bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl("Patient/2"); httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8))); status = ourClient.execute(httpPost); responseString = extractResponseAndClose(status); assertEquals(responseString, 403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; bundle.getEntry().clear(); bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl("Patient/1"); ourReturn = Collections.singletonList(responseBundle); ourDeleted = Collections.singletonList(createPatient(1)); httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8))); status = ourClient.execute(httpPost); responseString = extractResponseAndClose(status); assertEquals(responseString, 200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; bundle.getEntry().clear(); bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl("Observation?subject=Patient/2"); ourReturn = Collections.singletonList(responseBundle); ourDeleted = Collections.singletonList(createObservation(99, "Patient/2")); httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8))); status = ourClient.execute(httpPost); responseString = extractResponseAndClose(status); assertEquals(responseString, 403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; bundle.getEntry().clear(); bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl("Observation?subject=Patient/1"); ourReturn = Collections.singletonList(responseBundle); ourDeleted = Collections.singletonList(createObservation(99, "Patient/1")); httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8))); status = ourClient.execute(httpPost); responseString = extractResponseAndClose(status); assertEquals(responseString, 200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testDeleteByType() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").delete().resourcesOfType(Patient.class).withAnyId().andThen() .build(); } }); HttpDelete httpDelete; HttpResponse status; String responseString; ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient/1"); status = ourClient.execute(httpDelete); responseString = extractResponseAndClose(status); assertEquals(responseString, 204, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Observation/1"); status = ourClient.execute(httpDelete); responseString = extractResponseAndClose(status); assertEquals(responseString, 403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } /** * #528 */ @Test public void testDenyActionsNotOnTenant() throws Exception { ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy()); ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.ALLOW) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder().denyAll().notForTenantIds("TENANTA", "TENANTB").build(); } }); HttpGet httpGet; HttpResponse status; String response; ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTC/Patient/1"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by rule: (unnamed rule)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testDenyAll() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow().read().resourcesOfType(Patient.class).withAnyId().andThen() .denyAll("Default Rule") .build(); } @Override protected void handleDeny(Verdict decision) { // Make sure the toString() method on Verdict never fails ourLog.info("Denying with decision: {}", decision); super.handleDeny(decision); } }); HttpGet httpGet; HttpResponse status; String response; ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by rule: Default Rule")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$validate"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by rule: Default Rule")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by rule: Default Rule")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testDenyAllByDefault() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow().read().resourcesOfType(Patient.class).withAnyId().andThen() .build(); } @Override protected void handleDeny(Verdict decision) { // Make sure the toString() method on Verdict never fails ourLog.info("Denying with decision: {}", decision); super.handleDeny(decision); } }); HttpGet httpGet; HttpResponse status; String response; ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$validate"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } /** * #528 */ @Test public void testDenyByCompartmentWithAnyType() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder().deny("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a")).andThen().allowAll().build(); } }); HttpGet httpGet; HttpResponse status; ourHitMethod = false; ourReturn = Collections.singletonList(createCarePlan(10, "845bd9f1-3635-4866-a6c8-1ca085df5c1a")); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createCarePlan(10, "FOO")); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } /** * #528 */ @Test public void testDenyByCompartmentWithType() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder().deny("Rule 1").read().resourcesOfType(CarePlan.class).inCompartment("Patient", new IdType("Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a")).andThen().allowAll() .build(); } }); HttpGet httpGet; HttpResponse status; ourHitMethod = false; ourReturn = Collections.singletonList(createCarePlan(10, "845bd9f1-3635-4866-a6c8-1ca085df5c1a")); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createCarePlan(10, "FOO")); httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testHistoryWithReadAll() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().allResources().withAnyId() .build(); } }); HttpGet httpGet; HttpResponse status; ourReturn = Collections.singletonList(createPatient(2, 1)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/_history"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/_history"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/_history"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testInvalidInstanceIds() { try { new RuleBuilder().allow("Rule 1").write().instance((String) null); fail(); } catch (NullPointerException e) { assertEquals("theId must not be null or empty", e.getMessage()); } try { new RuleBuilder().allow("Rule 1").write().instance(""); fail(); } catch (IllegalArgumentException e) { assertEquals("theId must not be null or empty", e.getMessage()); } try { new RuleBuilder().allow("Rule 1").write().instance("Observation/"); fail(); } catch (IllegalArgumentException e) { assertEquals("theId must contain an ID part", e.getMessage()); } try { new RuleBuilder().allow("Rule 1").write().instance(new IdType()); fail(); } catch (NullPointerException e) { assertEquals("theId.getValue() must not be null or empty", e.getMessage()); } try { new RuleBuilder().allow("Rule 1").write().instance(new IdType("")); fail(); } catch (NullPointerException e) { assertEquals("theId.getValue() must not be null or empty", e.getMessage()); } try { new RuleBuilder().allow("Rule 1").write().instance(new IdType("Observation", (String) null)); fail(); } catch (NullPointerException e) { assertEquals("theId must contain an ID part", e.getMessage()); } } @Test public void testMetadataAllow() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").metadata() .build(); } }); HttpGet httpGet; HttpResponse status; ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/metadata"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); } @Test public void testMetadataDeny() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.ALLOW) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .deny("Rule 1").metadata() .build(); } }); HttpGet httpGet; HttpResponse status; ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/metadata"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); } @Test public void testOperationAnyName() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().withAnyName().onServer().andRequireExplicitResponseAuthorization().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; // Server ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); String response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testOperationAppliesAtAnyLevel() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().named("opName").atAnyLevel().andRequireExplicitResponseAuthorization().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // Server ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Type ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Instance ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Instance Version ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/_history/2/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testOperationAppliesAtAnyLevelWrongOpName() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().named("opNameBadOp").atAnyLevel().andRequireExplicitResponseAuthorization().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // Server ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Type ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Instance ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Instance Version ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/_history/2/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testOperationByInstanceOfTypeAllowed() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").operation().named("everything").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization() .build(); } }); HttpGet httpGet; HttpResponse status; String response; ourReturn = new ArrayList<>(); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$everything"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Bundle")); assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals(true, ourHitMethod); ourReturn = new ArrayList<>(); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Encounter/1/$everything"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("OperationOutcome")); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(false, ourHitMethod); } @Test public void testOperationByInstanceOfTypeWithInvalidReturnValue() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").operation().named("everything").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization().andThen() .allow("Rule 2").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // With a return value we don't allow ourReturn = Collections.singletonList(createPatient(222)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$everything"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("OperationOutcome")); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(true, ourHitMethod); // With a return value we do ourReturn = Collections.singletonList(createPatient(1)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$everything"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Bundle")); assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals(true, ourHitMethod); } @Test public void testOperationByInstanceOfTypeWithReturnValue() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").operation().named("everything").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization() .build(); } }); HttpGet httpGet; HttpResponse status; String response; ourReturn = new ArrayList<>(); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$everything"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Bundle")); assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals(true, ourHitMethod); ourReturn = new ArrayList<>(); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Encounter/1/$everything"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("OperationOutcome")); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(false, ourHitMethod); } @Test public void testOperationInstanceLevel() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().named("opName").onInstance(new IdType("http://example.com/Patient/1/_history/2")).andRequireExplicitResponseAuthorization().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // Server ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Type ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Instance ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Wrong instance ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testOperationInstanceLevelAnyInstance() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().named("opName").onAnyInstance().andRequireExplicitResponseAuthorization().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // Server ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Type ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Instance ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Another Instance ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/2/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Wrong name ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/$opName2"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testOperationNotAllowedWithWritePermissiom() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").write().allResources().withAnyId().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // Server ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // System ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Type ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Instance ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testOperationServerLevel() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().named("opName").onServer().andRequireExplicitResponseAuthorization().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // Server ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Type ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Instance ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testOperationTypeLevel() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().named("opName").onType(Patient.class).andRequireExplicitResponseAuthorization().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // Server ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Type ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Wrong type ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Wrong name ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName2"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Instance ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testOperationTypeLevelWildcard() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().named("opName").onAnyType().andRequireExplicitResponseAuthorization().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // Server ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Type ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Another type ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Wrong name ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName2"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Instance ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testOperationTypeLevelWithOperationMethodHavingOptionalIdParam() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().named("opName").onType(Organization.class).andRequireExplicitResponseAuthorization().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // Server ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Organization/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Type ourHitMethod = false; ourReturn = Collections.singletonList(createOrganization(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Organization/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Wrong type ourHitMethod = false; ourReturn = Collections.singletonList(createOrganization(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); // Instance ourHitMethod = false; ourReturn = Collections.singletonList(createOrganization(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Organization/1/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testOperationTypeLevelWithTenant() throws Exception { ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy()); ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().named("opName").onType(Patient.class).andRequireExplicitResponseAuthorization().forTenantIds("TENANTA").andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; // Right Tenant ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Wrong Tenant ourHitMethod = false; ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTC/Patient/$opName"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Access denied by default policy")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testOperationTypeLevelDifferentBodyType() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("RULE 1").operation().named("process-message").onServer().andRequireExplicitResponseAuthorization().andThen() .build(); } }); HttpPost httpPost; HttpResponse status; String response; Bundle input = new Bundle(); input.setType(Bundle.BundleType.MESSAGE); String inputString = ourCtx.newJsonParser().encodeResourceToString(input); // With body ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/$process-message"); httpPost.setEntity(new StringEntity(inputString, ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // With body ourHitMethod = false; HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/$process-message"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testOperationWithTester() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").operation().named("everything").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization().withTester(new IAuthRuleTester() { @Override public boolean matches(RestOperationTypeEnum theOperation, RequestDetails theRequestDetails, IIdType theInputResourceId, IBaseResource theInputResource) { return theInputResourceId.getIdPart().equals("1"); } }) .build(); } }); HttpGet httpGet; HttpResponse status; String response; ourReturn = new ArrayList<>(); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$everything"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Bundle")); assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals(true, ourHitMethod); ourReturn = new ArrayList<>(); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/$everything"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("OperationOutcome")); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(false, ourHitMethod); } @Test public void testPatchAllowed() throws IOException { Observation obs = new Observation(); obs.setSubject(new Reference("Patient/999")); ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow().patch().allRequests().andThen() .build(); } }); String patchBody = "[\n" + " { \"op\": \"replace\", \"path\": \"Observation/status\", \"value\": \"amended\" }\n" + " ]"; HttpPatch patch = new HttpPatch("http://localhost:" + ourPort + "/Observation/123"); patch.setEntity(new StringEntity(patchBody, ContentType.create(Constants.CT_JSON_PATCH, Charsets.UTF_8))); CloseableHttpResponse status = ourClient.execute(patch); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testPatchNotAllowed() throws IOException { Observation obs = new Observation(); obs.setSubject(new Reference("Patient/999")); ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow().metadata().andThen() .build(); } }); String patchBody = "[\n" + " { \"op\": \"replace\", \"path\": \"Observation/status\", \"value\": \"amended\" }\n" + " ]"; HttpPatch patch = new HttpPatch("http://localhost:" + ourPort + "/Observation/123"); patch.setEntity(new StringEntity(patchBody, ContentType.create(Constants.CT_JSON_PATCH, Charsets.UTF_8))); CloseableHttpResponse status = ourClient.execute(patch); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testGraphQLAllowed() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").graphQL().any().andThen() .build(); } }); HttpGet httpGet; HttpResponse status; String response; ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$graphql?query=" + UrlUtil.escapeUrlParam("{name}")); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testGraphQLDenied() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .build(); } }); HttpGet httpGet; HttpResponse status; String response; ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$graphql?query=" + UrlUtil.escapeUrlParam("{name}")); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testReadByAnyId() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().resourcesOfType(Patient.class).withAnyId() .build(); } }); HttpGet httpGet; HttpResponse status; String response; ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/_history/222"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourReturn = Arrays.asList(createPatient(1), createObservation(10, "Patient/2")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Arrays.asList(createPatient(2), createObservation(10, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testReadByAnyIdWithTenantId() throws Exception { ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy()); ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().resourcesOfType(Patient.class).withAnyId().forTenantIds("TENANTA") .build(); } }); HttpGet httpGet; HttpResponse status; String response; ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTB/Patient/1"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/1/_history/222"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourReturn = Arrays.asList(createPatient(1), createObservation(10, "Patient/2")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Arrays.asList(createPatient(2), createObservation(10, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testReadByAnyIdWithTester() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().resourcesOfType(Patient.class).withAnyId().withTester(new IAuthRuleTester() { @Override public boolean matches(RestOperationTypeEnum theOperation, RequestDetails theRequestDetails, IIdType theInputResourceId, IBaseResource theInputResource) { return theInputResourceId != null && theInputResourceId.getIdPart().equals("1"); } }) .build(); } }); HttpGet httpGet; HttpResponse status; String response; ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/_history/222"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourReturn = Arrays.asList(createPatient(1), createObservation(10, "Patient/2")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testReadByCompartmentReadByIdParam() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .build(); } }); HttpGet httpGet; HttpResponse status; ourReturn = Collections.singletonList(createPatient(1)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=Patient/1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createPatient(1)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=Patient/2"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testReadByCompartmentReadByPatientParam() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .build(); } }); HttpGet httpGet; HttpResponse status; ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?patient=Patient/1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?patient=1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?patient=Patient/2"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?subject=Patient/1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?subject=1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?subject=Patient/2"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testReadByCompartmentRight() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }); HttpGet httpGet; HttpResponse status; ourReturn = Collections.singletonList(createPatient(1)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createObservation(10, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Arrays.asList(createPatient(1), createObservation(10, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testReadByCompartmentWrongAllTypesProactiveBlockEnabledNoResponse() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .build(); } }.setFlags()); HttpGet httpGet; HttpResponse status; String response; ourReturn = Collections.emptyList(); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(404, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(404, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/_history"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/_history"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/999/_history"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testReadByCompartmentWrongProactiveBlockDisabled() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }.setFlags(AuthorizationFlagsEnum.NO_NOT_PROACTIVELY_BLOCK_COMPARTMENT_READ_ACCESS)); HttpGet httpGet; HttpResponse status; String response; ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourReturn = Collections.singletonList(createObservation(10, "Patient/2")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createCarePlan(10, "Patient/2")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourReturn = Arrays.asList(createPatient(1), createObservation(10, "Patient/2")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Arrays.asList(createPatient(2), createObservation(10, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertThat(response, containsString("Access denied by default policy (no applicable rules)")); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testReadByCompartmentWrongProactiveBlockDisabledNoResponse() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }.setFlags(AuthorizationFlagsEnum.NO_NOT_PROACTIVELY_BLOCK_COMPARTMENT_READ_ACCESS)); HttpGet httpGet; HttpResponse status; String response; ourReturn = Collections.emptyList(); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(404, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testReadByCompartmentWrongProactiveBlockEnabledNoResponse() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }.setFlags()); HttpGet httpGet; HttpResponse status; String response; ourReturn = Collections.emptyList(); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(404, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // CarePlan could potentially be in the Patient/1 compartment but we don't // have any rules explicitly allowing CarePlan so it's blocked ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/_history"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/_history"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/999/_history"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testReadByCompartmentDoesntAllowContained() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 2").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }.setFlags()); HttpGet httpGet; HttpResponse status; String response; // Read with allowed subject ourReturn = Lists.newArrayList(createObservation(10, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Read with contained ourReturn = Lists.newArrayList(createObservation(10, " ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Read with contained Observation obs = (Observation) createObservation(10, null); obs.setSubject(new Reference(new Patient().setActive(true))); ourReturn = Lists.newArrayList(obs); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testReadByInstance() throws Exception { ourConditionalCreateId = "1"; ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().instance("Observation/900").andThen() .allow("Rule 1").read().instance("901").andThen() .build(); } }); HttpResponse status; String response; HttpGet httpGet; ourReturn = Collections.singletonList(createObservation(900, "Patient/1")); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/900"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createPatient(901)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/901"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourReturn = Collections.singletonList(createPatient(1)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1?_format=json"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); } @Test public void testReadByInstanceAllowsTargetedSearch() throws Exception { ourConditionalCreateId = "1"; ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { RuleBuilder ruleBuilder = new RuleBuilder(); ruleBuilder.allow().read().instance("Patient/900").andThen(); ruleBuilder.allow().read().instance("Patient/700").andThen(); return ruleBuilder.build(); } }); HttpResponse status; String response; HttpGet httpGet; ourReturn = Collections.singletonList(createPatient(900)); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=900"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=Patient/900"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=901"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=Patient/901"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); ourHitMethod = false; // technically this is invalid, but just in case.. httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation?_id=Patient/901"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation?_id=901"); status = ourClient.execute(httpGet); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=Patient/900,Patient/700"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=900,777"); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testReadPageRight() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }); HttpGet httpGet; HttpResponse status; String respString; Bundle respBundle; ourReturn = new ArrayList<>(); for (int i = 0; i < 10; i++) { ourReturn.add(createObservation(i, "Patient/1")); } ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation?_count=5&_format=json&subject=Patient/1"); status = ourClient.execute(httpGet); respString = extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); respBundle = ourCtx.newJsonParser().parseResource(Bundle.class, respString); Assert.assertEquals(5, respBundle.getEntry().size()); Assert.assertEquals(10, respBundle.getTotal()); Assert.assertEquals("Observation/0", respBundle.getEntry().get(0).getResource().getIdElement().toUnqualifiedVersionless().getValue()); assertNotNull(respBundle.getLink("next")); // Load next page ourHitMethod = false; httpGet = new HttpGet(respBundle.getLink("next").getUrl()); status = ourClient.execute(httpGet); respString = extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); respBundle = ourCtx.newJsonParser().parseResource(Bundle.class, respString); Assert.assertEquals(5, respBundle.getEntry().size()); Assert.assertEquals(10, respBundle.getTotal()); Assert.assertEquals("Observation/5", respBundle.getEntry().get(0).getResource().getIdElement().toUnqualifiedVersionless().getValue()); assertNull(respBundle.getLink("next")); } @Test public void testReadPageWrong() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }); HttpGet httpGet; HttpResponse status; String respString; Bundle respBundle; ourReturn = new ArrayList<>(); for (int i = 0; i < 5; i++) { ourReturn.add(createObservation(i, "Patient/1")); } for (int i = 5; i < 10; i++) { ourReturn.add(createObservation(i, "Patient/2")); } ourHitMethod = false; httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation?_count=5&_format=json&subject=Patient/1"); status = ourClient.execute(httpGet); respString = extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); respBundle = ourCtx.newJsonParser().parseResource(Bundle.class, respString); Assert.assertEquals(5, respBundle.getEntry().size()); Assert.assertEquals(10, respBundle.getTotal()); Assert.assertEquals("Observation/0", respBundle.getEntry().get(0).getResource().getIdElement().toUnqualifiedVersionless().getValue()); assertNotNull(respBundle.getLink("next")); // Load next page ourHitMethod = false; httpGet = new HttpGet(respBundle.getLink("next").getUrl()); status = ourClient.execute(httpGet); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testTransactionWithSearch() throws IOException { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("transactions").transaction().withAnyOperation().andApplyNormalRules().andThen() .allow("read patient").read().resourcesOfType(Patient.class).withAnyId().andThen() .denyAll("deny all") .build(); } }); // Request is a transaction with 1 search Bundle requestBundle = new Bundle(); requestBundle.setType(Bundle.BundleType.TRANSACTION); String patientId = "10000003857"; Bundle.BundleEntryComponent bundleEntryComponent = requestBundle.addEntry(); Bundle.BundleEntryRequestComponent bundleEntryRequestComponent = new Bundle.BundleEntryRequestComponent(); bundleEntryRequestComponent.setMethod(Bundle.HTTPVerb.GET); bundleEntryRequestComponent.setUrl(ResourceType.Patient + "?identifier=" + patientId); bundleEntryComponent.setRequest(bundleEntryRequestComponent); /* * Response is a transaction response containing the search results */ Bundle searchResponseBundle = new Bundle(); Patient patent = new Patient(); patent.setActive(true); patent.setId("Patient/123"); searchResponseBundle.addEntry().setResource(patent); Bundle responseBundle = new Bundle(); responseBundle .addEntry() .setResource(searchResponseBundle); ourReturn = Collections.singletonList(responseBundle); HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(createFhirResourceEntity(requestBundle)); CloseableHttpResponse status = ourClient.execute(httpPost); String resp = extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); } @Test public void testTransactionWithNoBundleType() throws IOException { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("transactions").transaction().withAnyOperation().andApplyNormalRules().andThen() .allow("read patient").read().resourcesOfType(Patient.class).withAnyId().andThen() .denyAll("deny all") .build(); } }); // Request is a transaction with 1 search Bundle requestBundle = new Bundle(); String patientId = "10000003857"; Bundle.BundleEntryComponent bundleEntryComponent = requestBundle.addEntry(); Bundle.BundleEntryRequestComponent bundleEntryRequestComponent = new Bundle.BundleEntryRequestComponent(); bundleEntryRequestComponent.setMethod(Bundle.HTTPVerb.GET); bundleEntryRequestComponent.setUrl(ResourceType.Patient + "?identifier=" + patientId); bundleEntryComponent.setRequest(bundleEntryRequestComponent); HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(createFhirResourceEntity(requestBundle)); CloseableHttpResponse status = ourClient.execute(httpPost); String resp = extractResponseAndClose(status); assertEquals(422, status.getStatusLine().getStatusCode()); assertThat(resp, containsString("Invalid request Bundle.type value for transaction: \\\"\\\"")); } /** * See #762 */ @Test public void testTransactionWithPlaceholderIdsResponseAuthorized() throws IOException { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("transactions").transaction().withAnyOperation().andApplyNormalRules().andThen() .allow("read patient").read().resourcesOfType(Patient.class).withAnyId().andThen() .allow("write patient").write().resourcesOfType(Patient.class).withAnyId().andThen() .allow("write encounter").write().resourcesOfType(Encounter.class).withAnyId().andThen() .allow("write condition").write().resourcesOfType(Condition.class).withAnyId().andThen() .denyAll("deny all") .build(); } }); Bundle input = createTransactionWithPlaceholdersRequestBundle(); Bundle output = createTransactionWithPlaceholdersResponseBundle(); ourReturn = Collections.singletonList(output); HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(createFhirResourceEntity(input)); CloseableHttpResponse status = ourClient.execute(httpPost); String resp = extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); ourLog.info(resp); } /** * See #762 */ @Test public void testTransactionWithPlaceholderIdsResponseUnauthorized() throws IOException { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("transactions").transaction().withAnyOperation().andApplyNormalRules().andThen() .allow("write patient").write().resourcesOfType(Patient.class).withAnyId().andThen() .allow("write encounter").write().resourcesOfType(Encounter.class).withAnyId().andThen() .allow("write condition").write().resourcesOfType(Condition.class).withAnyId().andThen() .denyAll("deny all") .build(); } }); Bundle input = createTransactionWithPlaceholdersRequestBundle(); Bundle output = createTransactionWithPlaceholdersResponseBundle(); ourReturn = Collections.singletonList(output); HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(createFhirResourceEntity(input)); CloseableHttpResponse status = ourClient.execute(httpPost); String resp = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); ourLog.info(resp); } @Test public void testTransactionWriteGood() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").transaction().withAnyOperation().andApplyNormalRules().andThen() .allow("Rule 2").write().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen() .build(); } }); Bundle input = new Bundle(); input.setType(Bundle.BundleType.TRANSACTION); input.addEntry().setResource(createPatient(1)).getRequest().setUrl("/Patient").setMethod(Bundle.HTTPVerb.PUT); Bundle output = new Bundle(); output.setType(Bundle.BundleType.TRANSACTIONRESPONSE); output.addEntry().getResponse().setLocation("/Patient/1"); HttpPost httpPost; HttpResponse status; ourReturn = Collections.singletonList(output); ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/"); httpPost.setEntity(createFhirResourceEntity(input)); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); } @Test public void testWriteByCompartmentCreate() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 1b").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1123")).andThen() .allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }); HttpEntityEnclosingRequestBase httpPost; HttpResponse status; String response; ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); httpPost.setEntity(createFhirResourceEntity(createPatient(null))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); // Conditional ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); httpPost.addHeader("If-None-Exist", "Patient?foo=bar"); httpPost.setEntity(createFhirResourceEntity(createPatient(null))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/Observation"); httpPost.setEntity(createFhirResourceEntity(createObservation(null, "Patient/2"))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/Observation"); httpPost.setEntity(createFhirResourceEntity(createObservation(null, "Patient/1"))); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(201, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testWriteByCompartmentCreateConditionalResolvesToValid() throws Exception { ourConditionalCreateId = "1"; ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").createConditional().resourcesOfType(Patient.class) .build(); } }); HttpEntityEnclosingRequestBase httpPost; HttpResponse status; ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, "foo=bar"); httpPost.setEntity(createFhirResourceEntity(createPatient(null))); status = ourClient.execute(httpPost); String response = extractResponseAndClose(status); ourLog.info(response); assertEquals(201, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testWriteByCompartmentDeleteConditionalResolvesToValid() throws Exception { ourConditionalCreateId = "1"; ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").delete().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").deleteConditional().resourcesOfType(Patient.class) .build(); } }); HttpDelete httpDelete; HttpResponse status; ourReturn = Collections.singletonList(createPatient(1)); ourHitMethod = false; httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient?foo=bar"); status = ourClient.execute(httpDelete); String response = extractResponseAndClose(status); ourLog.info(response); assertEquals(204, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testWriteByCompartmentDeleteConditionalWithoutDirectMatch() throws Exception { ourConditionalCreateId = "1"; ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 2").deleteConditional().resourcesOfType(Patient.class).andThen() .allow().delete().instance(new IdType("Patient/2")).andThen() .build(); } }); HttpDelete httpDelete; HttpResponse status; String response; // Wrong resource ourReturn = Collections.singletonList(createPatient(1)); ourHitMethod = false; httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient?foo=bar"); status = ourClient.execute(httpDelete); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(403, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Right resource ourReturn = Collections.singletonList(createPatient(2)); ourHitMethod = false; httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient?foo=bar"); status = ourClient.execute(httpDelete); response = extractResponseAndClose(status); ourLog.info(response); assertEquals(204, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } @Test public void testWriteByCompartmentDoesntAllowDelete() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }); HttpDelete httpDelete; HttpResponse status; ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(2)); httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient/2"); status = ourClient.execute(httpDelete); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; ourReturn = Collections.singletonList(createPatient(1)); httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient/1"); status = ourClient.execute(httpDelete); extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testWriteByCompartmentUpdate() throws Exception { ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")) .build(); } }); HttpEntityEnclosingRequestBase httpPost; String response; HttpResponse status; ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/2"); httpPost.setEntity(createFhirResourceEntity(createPatient(2))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(ERR403, response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/1"); httpPost.setEntity(createFhirResourceEntity(createPatient(1))); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); // Conditional ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?foo=bar"); httpPost.setEntity(createFhirResourceEntity(createPatient(1))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(ERR403, response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?foo=bar"); httpPost.setEntity(createFhirResourceEntity(createPatient(99))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(ERR403, response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation/10"); httpPost.setEntity(createFhirResourceEntity(createObservation(10, "Patient/1"))); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation/10"); httpPost.setEntity(createFhirResourceEntity(createObservation(10, "Patient/2"))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(ERR403, response); assertEquals(403, status.getStatusLine().getStatusCode()); assertFalse(ourHitMethod); } @Test public void testWriteByCompartmentUpdateConditionalResolvesToInvalid() throws Exception { ourConditionalCreateId = "1123"; ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 3").updateConditional().resourcesOfType(Patient.class) .build(); } }); HttpEntityEnclosingRequestBase httpPost; HttpResponse status; String response; ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?foo=bar"); httpPost.setEntity(createFhirResourceEntity(createPatient(null))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertTrue(ourHitMethod); } @Test public void testWriteByCompartmentUpdateConditionalResolvesToValid() throws Exception { ourConditionalCreateId = "1"; ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 3").updateConditional().resourcesOfType(Patient.class) .build(); } }); HttpEntityEnclosingRequestBase httpPost; HttpResponse status; String response; ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?foo=bar"); httpPost.setEntity(createFhirResourceEntity(createPatient(null))); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation?foo=bar"); httpPost.setEntity(createFhirResourceEntity(createObservation(null, "Patient/12"))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); } @Test public void testWriteByCompartmentUpdateConditionalResolvesToValidAllTypes() throws Exception { ourConditionalCreateId = "1"; ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")).andThen() .allow("Rule 3").updateConditional().allResources() .build(); } }); HttpEntityEnclosingRequestBase httpPost; HttpResponse status; String response; ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?foo=bar"); httpPost.setEntity(createFhirResourceEntity(createPatient(null))); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation?foo=bar"); httpPost.setEntity(createFhirResourceEntity(createObservation(null, "Patient/12"))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertTrue(ourHitMethod); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); } @Test public void testWriteByInstance() throws Exception { ourConditionalCreateId = "1"; ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").write().instance("Observation/900").andThen() .allow("Rule 1").write().instance("901").andThen() .build(); } }); HttpEntityEnclosingRequestBase httpPost; HttpResponse status; String response; ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation/900"); httpPost.setEntity(createFhirResourceEntity(createObservation(900, "Patient/12"))); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation/901"); httpPost.setEntity(createFhirResourceEntity(createObservation(901, "Patient/12"))); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/Observation"); httpPost.setEntity(createFhirResourceEntity(createObservation(null, "Patient/900"))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); ourHitMethod = false; httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); httpPost.setEntity(createFhirResourceEntity(createPatient(null))); status = ourClient.execute(httpPost); response = extractResponseAndClose(status); assertEquals(403, status.getStatusLine().getStatusCode()); assertEquals(ERR403, response); assertFalse(ourHitMethod); } @Test public void testWritePatchByInstance() throws Exception { ourConditionalCreateId = "1"; ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() .allow("Rule 1").patch().allRequests().andThen() .allow("Rule 1").write().instance("Patient/900").andThen() .build(); } }); HttpEntityEnclosingRequestBase httpPost; HttpResponse status; String input = "[ { \"op\": \"replace\", \"path\": \"/gender\", \"value\": \"male\" } ]"; ourHitMethod = false; httpPost = new HttpPatch("http://localhost:" + ourPort + "/Patient/900"); httpPost.setEntity(new StringEntity(input, ContentType.parse("application/json-patch+json"))); status = ourClient.execute(httpPost); extractResponseAndClose(status); assertEquals(200, status.getStatusLine().getStatusCode()); assertTrue(ourHitMethod); } public static class DummyCarePlanResourceProvider implements IResourceProvider { @Override public Class<? extends IBaseResource> getResourceType() { return CarePlan.class; } @Read(version = true) public CarePlan read(@IdParam IdType theId) { ourHitMethod = true; if (ourReturn.isEmpty()) { throw new ResourceNotFoundException(theId); } return (CarePlan) ourReturn.get(0); } @Search() public List<Resource> search() { ourHitMethod = true; return ourReturn; } } @SuppressWarnings("unused") public static class DummyEncounterResourceProvider implements IResourceProvider { @Operation(name = "everything", idempotent = true) public Bundle everything(@IdParam IdType theId) { ourHitMethod = true; Bundle retVal = new Bundle(); for (Resource next : ourReturn) { retVal.addEntry().setResource(next); } return retVal; } @Override public Class<? extends IBaseResource> getResourceType() { return Encounter.class; } } public static class DummyOrganizationResourceProvider implements IResourceProvider { @Override public Class<? extends IBaseResource> getResourceType() { return Organization.class; } /** * This should come before operation1 */ @Operation(name = "opName", idempotent = true) public Parameters operation0(@IdParam(optional = true) IdType theId) { ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } } public static class DummyDiagnosticReportResourceProvider implements IResourceProvider { @Override public Class<? extends IBaseResource> getResourceType() { return DiagnosticReport.class; } @Search() public List<Resource> search( @OptionalParam(name = "subject") ReferenceParam theSubject, @OptionalParam(name = "patient") ReferenceParam thePatient ) { ourHitMethod = true; return ourReturn; } } @SuppressWarnings("unused") public static class DummyObservationResourceProvider implements IResourceProvider { @Create() public MethodOutcome create(@ResourceParam Observation theResource, @ConditionalUrlParam String theConditionalUrl) { ourHitMethod = true; theResource.setId("Observation/1/_history/1"); MethodOutcome retVal = new MethodOutcome(); retVal.setCreated(true); retVal.setResource(theResource); return retVal; } @Delete() public MethodOutcome delete(@IdParam IdType theId) { ourHitMethod = true; return new MethodOutcome(); } @Override public Class<? extends IBaseResource> getResourceType() { return Observation.class; } /** * This should come before operation1 */ @Operation(name = "opName", idempotent = true) public Parameters operation0(@IdParam IdType theId) { ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } /** * This should come after operation0 */ @Operation(name = "opName", idempotent = true) public Parameters operation1() { ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } @Patch public MethodOutcome patch(@IdParam IdType theId, PatchTypeEnum thePatchType, @ResourceParam String theBody) { ourHitMethod = true; return new MethodOutcome().setId(theId.withVersion("2")); } @Read(version = true) public Observation read(@IdParam IdType theId) { ourHitMethod = true; if (ourReturn.isEmpty()) { throw new ResourceNotFoundException(theId); } return (Observation) ourReturn.get(0); } @Search() public List<Resource> search( @OptionalParam(name = "_id") TokenAndListParam theIds, @OptionalParam(name = "subject") ReferenceParam theSubject) { ourHitMethod = true; return ourReturn; } @Update() public MethodOutcome update(@IdParam IdType theId, @ResourceParam Observation theResource, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) { ourHitMethod = true; if (isNotBlank(theConditionalUrl)) { IdType actual = new IdType("Observation", ourConditionalCreateId); ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, actual); subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE); theResource.setId(actual); } else { ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, theResource); subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE); theResource.setId(theId.withVersion("2")); } MethodOutcome retVal = new MethodOutcome(); retVal.setResource(theResource); return retVal; } } @SuppressWarnings("unused") public static class DummyPatientResourceProvider implements IResourceProvider { @Create() public MethodOutcome create(@ResourceParam Patient theResource, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) { if (isNotBlank(theConditionalUrl)) { IdType actual = new IdType("Patient", ourConditionalCreateId); ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, actual); subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.CREATE); } else { ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, theResource); subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.CREATE); } ourHitMethod = true; theResource.setId("Patient/1/_history/1"); MethodOutcome retVal = new MethodOutcome(); retVal.setCreated(true); retVal.setResource(theResource); return retVal; } @Delete() public MethodOutcome delete(IInterceptorBroadcaster theRequestOperationCallback, @IdParam IdType theId, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) { ourHitMethod = true; for (IBaseResource next : ourReturn) { HookParams params = new HookParams() .add(IBaseResource.class, next) .add(RequestDetails.class, theRequestDetails) .addIfMatchesType(ServletRequestDetails.class, theRequestDetails); theRequestOperationCallback.callHooks(Pointcut.STORAGE_PRESTORAGE_RESOURCE_DELETED, params); } return new MethodOutcome(); } @Operation(name = "everything", idempotent = true) public Bundle everything(@IdParam IdType theId) { ourHitMethod = true; Bundle retVal = new Bundle(); for (Resource next : ourReturn) { retVal.addEntry().setResource(next); } return retVal; } @Override public Class<? extends IBaseResource> getResourceType() { return Patient.class; } @History() public List<Resource> history() { ourHitMethod = true; return (ourReturn); } @History() public List<Resource> history(@IdParam IdType theId) { ourHitMethod = true; return (ourReturn); } @Operation(name = "opName", idempotent = true) public Parameters operation0(@IdParam IdType theId) { ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } /** * More generic method second to make sure that the * other method takes precedence */ @Operation(name = "opName", idempotent = true) public Parameters operation1() { ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } @Operation(name = "opName2", idempotent = true) public Parameters operation2(@IdParam IdType theId) { ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } @Operation(name = "opName2", idempotent = true) public Parameters operation2() { ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } @Patch() public MethodOutcome patch(@IdParam IdType theId, @ResourceParam String theResource, PatchTypeEnum thePatchType) { ourHitMethod = true; MethodOutcome retVal = new MethodOutcome(); return retVal; } @Read(version = true) public Patient read(@IdParam IdType theId) { ourHitMethod = true; if (ourReturn.isEmpty()) { throw new ResourceNotFoundException(theId); } return (Patient) ourReturn.get(0); } @Search() public List<Resource> search(@OptionalParam(name = "_id") TokenAndListParam theIdParam) { ourHitMethod = true; return ourReturn; } @Update() public MethodOutcome update(@IdParam IdType theId, @ResourceParam Patient theResource, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) { ourHitMethod = true; if (isNotBlank(theConditionalUrl)) { IdType actual = new IdType("Patient", ourConditionalCreateId); ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, actual); subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE); theResource.setId(actual); } else { ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, theResource); subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE); theResource.setId(theId.withVersion("2")); } MethodOutcome retVal = new MethodOutcome(); retVal.setResource(theResource); return retVal; } @Validate public MethodOutcome validate(@ResourceParam Patient theResource, @IdParam IdType theId, @ResourceParam String theRawResource, @ResourceParam EncodingEnum theEncoding, @Validate.Mode ValidationModeEnum theMode, @Validate.Profile String theProfile, RequestDetails theRequestDetails) { ourHitMethod = true; OperationOutcome oo = new OperationOutcome(); oo.addIssue().setDiagnostics("OK"); return new MethodOutcome(oo); } @Validate public MethodOutcome validate(@ResourceParam Patient theResource, @ResourceParam String theRawResource, @ResourceParam EncodingEnum theEncoding, @Validate.Mode ValidationModeEnum theMode, @Validate.Profile String theProfile, RequestDetails theRequestDetails) { ourHitMethod = true; OperationOutcome oo = new OperationOutcome(); oo.addIssue().setDiagnostics("OK"); return new MethodOutcome(oo); } } public static class PlainProvider { @History() public List<Resource> history() { ourHitMethod = true; return (ourReturn); } @Operation(name = "opName", idempotent = true) public Parameters operation() { ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } @Operation(name = "process-message", idempotent = true) public Parameters processMessage(@OperationParam(name = "content") Bundle theInput) { ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } @GraphQL public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQuery String theQuery) { ourHitMethod = true; return "{'foo':'bar'}"; } @Transaction() public Bundle search(ServletRequestDetails theRequestDetails, IInterceptorBroadcaster theInterceptorBroadcaster, @TransactionParam Bundle theInput) { ourHitMethod = true; if (ourDeleted != null) { for (IBaseResource next : ourDeleted) { HookParams params = new HookParams() .add(IBaseResource.class, next) .add(RequestDetails.class, theRequestDetails) .add(ServletRequestDetails.class, theRequestDetails); theInterceptorBroadcaster.callHooks(Pointcut.STORAGE_PRESTORAGE_RESOURCE_DELETED, params); } } return (Bundle) ourReturn.get(0); } } @AfterClass public static void afterClassClearContext() throws Exception { JettyUtil.closeServer(ourServer); TestUtil.clearAllStaticFieldsForUnitTest(); } @BeforeClass public static void beforeClass() throws Exception { ourServer = new Server(0); DummyPatientResourceProvider patProvider = new DummyPatientResourceProvider(); DummyObservationResourceProvider obsProv = new DummyObservationResourceProvider(); DummyOrganizationResourceProvider orgProv = new DummyOrganizationResourceProvider(); DummyEncounterResourceProvider encProv = new DummyEncounterResourceProvider(); DummyCarePlanResourceProvider cpProv = new DummyCarePlanResourceProvider(); DummyDiagnosticReportResourceProvider drProv = new DummyDiagnosticReportResourceProvider(); PlainProvider plainProvider = new PlainProvider(); ServletHandler proxyHandler = new ServletHandler(); ourServlet = new RestfulServer(ourCtx); ourServlet.setFhirContext(ourCtx); ourServlet.setResourceProviders(patProvider, obsProv, encProv, cpProv, orgProv, drProv); ourServlet.setPlainProviders(plainProvider); ourServlet.setPagingProvider(new FifoMemoryPagingProvider(100)); ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); ServletHolder servletHolder = new ServletHolder(ourServlet);</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1290"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.helioviewer.plugins.eveplugin.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import org.helioviewer.base.math.Interval; import org.helioviewer.jhv.gui.IconBank; import org.helioviewer.jhv.gui.IconBank.JHVIcon; import org.helioviewer.jhv.gui.dialogs.observation.ObservationDialog; import org.helioviewer.jhv.layers.LayersListener; import org.helioviewer.jhv.layers.LayersModel; import org.helioviewer.plugins.eveplugin.controller.ZoomController; import org.helioviewer.plugins.eveplugin.events.model.EventModel; import org.helioviewer.plugins.eveplugin.events.model.EventModelListener; import org.helioviewer.plugins.eveplugin.settings.EVESettings; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDataSelectorPanel; import org.helioviewer.viewmodel.view.View; /** * * * @author Bram Bourgoignie (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d597a7b4b8fb97baa0a7b2babcb2bbbcb095bab8b4fbb7b0">[email protected]</a>) * */ public class ControlsPanel extends JPanel implements ActionListener, LayersListener, EventModelListener { private static final long serialVersionUID = 3639870635351984819L; private static ControlsPanel singletongInstance; private final JPanel lineDataSelectorContainer = new JPanel(); private final ImageIcon addIcon = IconBank.getIcon(JHVIcon.ADD); private final JButton addLayerButton = new JButton("Add Layer", addIcon); // private final String[] plots = { "No Events", "Events on Plot 1", // "Events on Plot 2" }; // private final JComboBox eventsComboBox = new JComboBox(plots); private final JCheckBox eventsCheckBox = new JCheckBox(); private final JLabel eventsLabel = new JLabel("Display events: "); private final ImageIcon movietimeIcon = IconBank.getIcon(JHVIcon.LAYER_MOVIE_TIME); private final JButton periodFromLayersButton = new JButton(movietimeIcon); private ControlsPanel() { initVisualComponents(); LayersModel.getSingletonInstance().addLayersListener(this); } private void initVisualComponents() { EventModel.getSingletonInstance().addEventModelListener(this); eventsCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (eventsCheckBox.isSelected()) { EventModel.getSingletonInstance().activateEvents(); } else { EventModel.getSingletonInstance().deactivateEvents(); } } }); addLayerButton.setToolTipText("Add a new layer"); addLayerButton.addActionListener(this); periodFromLayersButton.setToolTipText("Request data of selected movie interval"); periodFromLayersButton.setPreferredSize(new Dimension(movietimeIcon.getIconWidth() + 14, periodFromLayersButton.getPreferredSize().height)); periodFromLayersButton.addActionListener(this); setEnabledStateOfPeriodMovieButton(); // this.setPreferredSize(new Dimension(100, 300)); lineDataSelectorContainer.setLayout(new BoxLayout(lineDataSelectorContainer, BoxLayout.Y_AXIS)); lineDataSelectorContainer.setPreferredSize(new Dimension(100, 130)); this.setLayout(new BorderLayout()); add(lineDataSelectorContainer, BorderLayout.CENTER); JPanel pageEndPanel = new JPanel(); pageEndPanel.setBackground(Color.BLUE); JPanel flowPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); flowPanel.add(eventsLabel); flowPanel.add(eventsCheckBox); flowPanel.add(periodFromLayersButton); flowPanel.add(addLayerButton); add(flowPanel, BorderLayout.PAGE_END); } public static ControlsPanel getSingletonInstance() { if (singletongInstance == null) { singletongInstance = new ControlsPanel(); } return singletongInstance; } public void addLineDataSelector(LineDataSelectorPanel lineDataSelectorPanel) { lineDataSelectorContainer.add(lineDataSelectorPanel); } public void removeLineDataSelector(LineDataSelectorPanel lineDataSelectorPanel) { lineDataSelectorContainer.remove(lineDataSelectorPanel); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource().equals(addLayerButton)) { ObservationDialog.getSingletonInstance().showDialog(EVESettings.OBSERVATION_UI_NAME); } else if (e.getSource() == periodFromLayersButton) { final Interval<Date> interval = new Interval<Date>(LayersModel.getSingletonInstance().getFirstDate(), LayersModel .getSingletonInstance().getLastDate()); ZoomController.getSingletonInstance().setSelectedInterval(interval, true); } } private void setEnabledStateOfPeriodMovieButton() { final Interval<Date> frameInterval = LayersModel.getSingletonInstance().getFrameInterval(); periodFromLayersButton.setEnabled(frameInterval.getStart() != null && frameInterval.getEnd() != null); } @Override public void layerAdded(int idx) { if (EventQueue.isDispatchThread()) { setEnabledStateOfPeriodMovieButton(); } else { EventQueue.invokeLater(new Runnable() { @Override public void run() { setEnabledStateOfPeriodMovieButton(); } }); } } @Override public void layerRemoved(View oldView, int oldIdx) { if (EventQueue.isDispatchThread()) { setEnabledStateOfPeriodMovieButton(); } else { EventQueue.invokeLater(new Runnable() { @Override public void run() { setEnabledStateOfPeriodMovieButton(); } }); } } @Override public void layerChanged(int idx) { // TODO Auto-generated method stub } @Override public void activeLayerChanged(int idx) { // TODO Auto-generated method stub } @Override public void viewportGeometryChanged() { // TODO Auto-generated method stub } @Override public void timestampChanged(int idx) { // TODO Auto-generated method stub } @Override public void subImageDataChanged() { // TODO Auto-generated method stub } @Override public void layerDownloaded(int idx) { // TODO Auto-generated method stub } @Override public void eventsDeactivated() { eventsCheckBox.setSelected(false); repaint(); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1291"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.highcharts.export.pool; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.log4j.Logger; import com.highcharts.export.server.Server; import com.highcharts.export.server.ServerState; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.commons.io.IOUtils; public class ServerObjectFactory implements ObjectFactory<Server> { public String exec; public String script; private String host; private int basePort; private int readTimeout; private int connectTimeout; private int maxTimeout; public static String tmpDir = System.getProperty("java.io.tmpdir"); private static HashMap<Integer, PortStatus> portUsage = new HashMap<Integer, PortStatus>(); protected static Logger logger = Logger.getLogger("pool"); private enum PortStatus { BUSY, FREE; } @Override public Server create() { logger.debug("in makeObject, " + exec + ", " + script + ", " + host); Integer port = this.getAvailablePort(); portUsage.put(port, PortStatus.BUSY); return new Server(exec, script, host, port, connectTimeout, readTimeout, maxTimeout); } @Override public boolean validate(Server server) { boolean isValid = false; try { if(server.getState() != ServerState.IDLE) { logger.debug("server didn\'t pass validation"); return false; } String result = server.request("{\"status\":\"isok\"}"); if(result.indexOf("OK") > -1) { isValid = true; logger.debug("server passed validation"); } else { logger.debug("server didn\'t pass validation"); } } catch (Exception e) { logger.error("Error while validating object in Pool: " + e.getMessage()); } return isValid; } @Override public void destroy(Server server) { ServerObjectFactory.releasePort(server.getPort()); server.cleanup(); } @Override public void activate(Server server) { server.setState(ServerState.ACTIVE); } @Override public void passivate(Server server) { server.setState(ServerState.IDLE); } public static void releasePort(Integer port) { logger.debug("Releasing port " + port); portUsage.put(port, PortStatus.FREE); } public Integer getAvailablePort() { for (Map.Entry<Integer, PortStatus> entry : portUsage.entrySet()) { if (PortStatus.FREE == entry.getValue()) { // return available port logger.debug("Portusage " + portUsage.toString()); return entry.getKey(); } } // if no port is free logger.debug("Nothing free in Portusage " + portUsage.toString()); return basePort + portUsage.size(); } /*Getters and Setters*/ public String getExec() { return exec; } public void setExec(String exec) { this.exec = exec; } public String getScript() { return script; } public void setScript(String script) { this.script = script; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getBasePort() { return basePort; } public void setBasePort(int basePort) { this.basePort = basePort; } public int getReadTimeout() { return readTimeout; } public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public int getMaxTimeout() { return maxTimeout; } public void setMaxTimeout(int maxTimeout) { this.maxTimeout = maxTimeout; } @PostConstruct public void afterBeanInit() { String jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); try { jarLocation = URLDecoder.decode(jarLocation, "utf-8"); // get filesystem depend path jarLocation = new File(jarLocation).getCanonicalPath(); } catch (UnsupportedEncodingException ueex) { logger.error(ueex); } catch (IOException ioex) { logger.error(ioex); } try { JarFile jar = new JarFile(jarLocation); for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.startsWith("phantomjs/")) { File file = new File(tmpDir + name); if (name.endsWith("/")) { file.mkdir(); } else { InputStream in = jar.getInputStream(entry); IOUtils.copy(in, new FileOutputStream(file)); } } } } catch (IOException ioex) { logger.error(ioex); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1292"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package net.ttddyy.evernote.rest; import org.junit.Test; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; /** * Miscellaneous tests for {@link StoreOperationController}. * * @author Tadaya Tsuyukubo */ public class StoreOperationControllerMiscIntegrationTest extends AbstractStoreOperationControllerIntegrationTest { @Test public void testNoInputForNoParameterMethod() throws Exception { given(userStoreOperations.isBusinessUser()).willReturn(true); mockMvc.perform(post("/userStore/isBusinessUser")); verify(userStoreOperations).isBusinessUser(); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1293"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.springframework.data.gclouddatastore.repository; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.instanceOf; import java.net.URI; import java.nio.charset.Charset; import java.time.Instant; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZonedDateTime; import java.time.ZoneId; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import lombok.Data; import lombok.NoArgsConstructor; import org.junit.Assert; import org.junit.Test; import org.springframework.data.gclouddatastore.repository.Unmarshaller; import org.springframework.data.annotation.Id; import com.google.cloud.Timestamp; import com.google.cloud.datastore.Blob; import com.google.cloud.datastore.DoubleValue; import com.google.cloud.datastore.Entity; import com.google.cloud.datastore.Key; import com.google.cloud.datastore.LongValue; import com.google.cloud.datastore.StringValue; public class UnmarshallerTest { @Data @NoArgsConstructor public static class TestBean { @Id long id; Object object; byte[] bytes; String string; Boolean boxedBoolean; boolean primitiveBoolean; Double boxedDouble; double primitiveDouble; Float boxedFloat; float primitiveFloat; Long boxedLong; long primitiveLong; Integer boxedInteger; int primitiveInt; Short boxedShort; short primitiveShort; Byte boxedByte; byte primitiveByte; List<?> list; LinkedList<?> linkedList; Map<String, Object> map; URI uri; Instant instant; Date date; Calendar calendar; java.sql.Timestamp sqlTimestamp; LocalDateTime localDateTime; OffsetDateTime offsetDateTime; ZonedDateTime zonedDateTime; } @Test public void testUnmarshalToObject_Blob() { //Setup byte[] hello = "hello".getBytes(Charset.forName("UTF-8")); Key key = Key.newBuilder("project", "kind", 1).build(); Entity entity = Entity.newBuilder(key) .set("object", Blob.copyFrom(hello)) .set("bytes", Blob.copyFrom(hello)) .set("string", Blob.copyFrom(hello)) .build(); Unmarshaller unmarshaller = new Unmarshaller(); TestBean bean = new TestBean(); // Exercise unmarshaller.unmarshalToObject(entity, bean); // Verify Assert.assertArrayEquals(hello, (byte[])bean.object); Assert.assertArrayEquals(hello, bean.bytes); Assert.assertEquals("hello", bean.string); } @Test public void testUnmarshalToObject_Boolean() { //Setup Key key = Key.newBuilder("project", "kind", 1).build(); Entity entity = Entity.newBuilder(key) .set("object", true) .set("boxedBoolean", true) .set("primitiveBoolean", true) .build(); Unmarshaller unmarshaller = new Unmarshaller(); TestBean bean = new TestBean(); // Exercise unmarshaller.unmarshalToObject(entity, bean); // Verify Assert.assertEquals(Boolean.TRUE, bean.object); Assert.assertEquals(Boolean.TRUE, bean.boxedBoolean); Assert.assertTrue(bean.primitiveBoolean); } @Test public void testUnmarshalToObject_Double() { //Setup Key key = Key.newBuilder("project", "kind", 1).build(); Entity entity = Entity.newBuilder(key) .set("object", 3.14) .set("boxedDouble", 3.14) .set("primitiveDouble", 3.14) .set("boxedFloat", 3.14) .set("primitiveFloat", 3.14) .set("boxedLong", 3.14) .set("primitiveLong", 3.14) .set("boxedInteger", 3.14) .set("primitiveInt", 3.14) .set("boxedShort", 3.14) .set("primitiveShort", 3.14) .set("boxedByte", 3.14) .set("primitiveByte", 3.14) .build(); Unmarshaller unmarshaller = new Unmarshaller(); TestBean bean = new TestBean(); // Exercise unmarshaller.unmarshalToObject(entity, bean); // Verify Assert.assertEquals(Double.valueOf(3.14), bean.object); Assert.assertEquals(Double.valueOf(3.14), bean.boxedDouble); Assert.assertEquals(3.14, bean.primitiveDouble, 0.0); Assert.assertEquals(Float.valueOf(3.14f), bean.boxedFloat); Assert.assertEquals(3.14f, bean.primitiveFloat, 0.0f); Assert.assertEquals(Long.valueOf(3L), bean.boxedLong); Assert.assertEquals(3, bean.primitiveLong); Assert.assertEquals(Integer.valueOf(3), bean.boxedInteger); Assert.assertEquals(3, bean.primitiveInt); Assert.assertEquals(Short.valueOf((short)3), bean.boxedShort); Assert.assertEquals(3, bean.primitiveShort); Assert.assertEquals(Byte.valueOf((byte)3), bean.boxedByte); Assert.assertEquals(3, bean.primitiveByte); } @Test public void testUnmarshalToObject_Long() { //Setup Key key = Key.newBuilder("project", "kind", 1).build(); Entity entity = Entity.newBuilder(key) .set("object", 42) .set("boxedLong", 42) .set("primitiveLong", 42) .set("boxedInteger", 42) .set("primitiveInt", 42) .set("boxedShort", 42) .set("primitiveShort", 42) .set("boxedByte", 42) .set("primitiveByte", 42) .set("boxedDouble", 42) .set("primitiveDouble", 42) .set("boxedFloat", 42) .set("primitiveFloat", 42) .build(); Unmarshaller unmarshaller = new Unmarshaller(); TestBean bean = new TestBean(); // Exercise unmarshaller.unmarshalToObject(entity, bean); // Verify Assert.assertEquals(Long.valueOf(42), bean.object); Assert.assertEquals(Long.valueOf(42), bean.boxedLong); Assert.assertEquals(42L, bean.primitiveLong); Assert.assertEquals(Integer.valueOf(42), bean.boxedInteger); Assert.assertEquals(42, bean.primitiveInt); Assert.assertEquals(Short.valueOf((short)42), bean.boxedShort); Assert.assertEquals(42, bean.primitiveShort); Assert.assertEquals(Byte.valueOf((byte)42), bean.boxedByte); Assert.assertEquals(42, bean.primitiveByte); Assert.assertEquals(Double.valueOf(42.0), bean.boxedDouble); Assert.assertEquals(42.0, bean.primitiveDouble, 0.0); Assert.assertEquals(Float.valueOf(42.0f), bean.boxedFloat); Assert.assertEquals(42.0f, bean.primitiveFloat, 0.0f); } @Test public void testUnmarshalToObject_String() throws Exception { //Setup Key key = Key.newBuilder("project", "kind", 1).build(); Entity entity = Entity.newBuilder(key) .set("object", "hello") .set("string", "hello") .set("bytes", "hello") .set("boxedLong", "42") .set("primitiveLong", "42") .set("boxedInteger", "42") .set("primitiveInt", "42") .set("boxedShort", "42") .set("primitiveShort", "42") .set("boxedByte", "42") .set("primitiveByte", "42") .set("boxedDouble", "3.14") .set("primitiveDouble", "3.14") .set("boxedFloat", "3.14") .set("primitiveFloat", "3.14") .set("uri", "https://example.com") .build(); Unmarshaller unmarshaller = new Unmarshaller(); TestBean bean = new TestBean(); // Exercise unmarshaller.unmarshalToObject(entity, bean); // Verify Assert.assertEquals("hello", bean.object); Assert.assertEquals("hello", bean.string); Assert.assertArrayEquals("hello".getBytes(Charset.forName("UTF-8")), bean.bytes); Assert.assertEquals(Long.valueOf(42), bean.boxedLong); Assert.assertEquals(42L, bean.primitiveLong); Assert.assertEquals(Integer.valueOf(42), bean.boxedInteger); Assert.assertEquals(42, bean.primitiveInt); Assert.assertEquals(Short.valueOf((short)42), bean.boxedShort); Assert.assertEquals(42, bean.primitiveShort); Assert.assertEquals(Byte.valueOf((byte)42), bean.boxedByte); Assert.assertEquals(42, bean.primitiveByte); Assert.assertEquals(Double.valueOf(3.14), bean.boxedDouble); Assert.assertEquals(3.14, bean.primitiveDouble, 0.0); Assert.assertEquals(Float.valueOf(3.14f), bean.boxedFloat); Assert.assertEquals(3.14f, bean.primitiveFloat, 0.0f); Assert.assertEquals(new URI("https://example.com"), bean.uri); } @Test public void testUnmarshalToObject_List() { //Setup Key key = Key.newBuilder("project", "kind", 1).build(); Entity entity = Entity.newBuilder(key) .set("object", Arrays.asList(DoubleValue.of(3.14), LongValue.of(42), StringValue.of("hello"))) .set("list", Arrays.asList(DoubleValue.of(3.14), LongValue.of(42), StringValue.of("hello"))) .set("linkedList", Arrays.asList(DoubleValue.of(3.14), LongValue.of(42), StringValue.of("hello"))) .build(); Unmarshaller unmarshaller = new Unmarshaller(); TestBean bean = new TestBean(); bean.linkedList = new LinkedList<Object>(); // Exercise unmarshaller.unmarshalToObject(entity, bean); // Verify Assert.assertThat((List<?>)bean.object, contains(3.14, 42L, "hello")); Assert.assertThat(bean.list, contains(3.14, 42L, "hello")); Assert.assertThat(bean.linkedList, contains(3.14, 42L, "hello")); Assert.assertThat(bean.linkedList, instanceOf(LinkedList.class)); } @Test public void testUnmarshalToObject_Map1() { //Setup Key key = Key.newBuilder("project", "kind", 1).build(); Entity entity = Entity.newBuilder(key) .set("object", Entity.newBuilder().set("k", "v").build()) .set("map", Entity.newBuilder().set("k", "v").build()) .build(); Unmarshaller unmarshaller = new Unmarshaller(); TestBean bean = new TestBean(); // Exercise unmarshaller.unmarshalToObject(entity, bean); // Verify Map<String, Object> expected = new HashMap<>(); expected.put("k", "v"); Assert.assertEquals(expected, bean.object); Assert.assertEquals(expected, bean.map); } @Test public void testUnmarshalToObject_Map2() { //Setup Key key = Key.newBuilder("project", "kind", 1).build(); Entity entity = Entity.newBuilder(key) .set("object", Entity.newBuilder().set("k1", Entity.newBuilder().set("k2", "v2").build()).build()) .set("map", Entity.newBuilder().set("k1", Entity.newBuilder().set("k2", "v2").build()).build()) .build(); Unmarshaller unmarshaller = new Unmarshaller(); TestBean bean = new TestBean(); // Exercise unmarshaller.unmarshalToObject(entity, bean); // Verify Map<String, Object> innerMap = new HashMap<>(); innerMap.put("k2", "v2"); Map<String, Object> expected = new HashMap<>(); expected.put("k1", innerMap); Assert.assertEquals(expected, bean.object); Assert.assertEquals(expected, bean.map); } @Test public void testUnmarshalToObject_Timestamp() { //Setup Key key = Key.newBuilder("project", "kind", 1).build(); Entity entity = Entity.newBuilder(key) .set("object", Timestamp.parseTimestamp("2017-07-09T12:34:56Z")) .set("primitiveLong", Timestamp.parseTimestamp("2017-07-09T12:34:56Z")) .set("boxedLong", Timestamp.parseTimestamp("2017-07-09T12:34:56Z")) .set("date", Timestamp.parseTimestamp("2017-07-09T12:34:56Z")) .set("calendar", Timestamp.parseTimestamp("2017-07-09T12:34:56Z")) .set("sqlTimestamp", Timestamp.parseTimestamp("2017-07-09T12:34:56Z")) .set("localDateTime", Timestamp.parseTimestamp("2017-07-09T12:34:56Z")) .set("offsetDateTime", Timestamp.parseTimestamp("2017-07-09T12:34:56Z")) .set("zonedDateTime", Timestamp.parseTimestamp("2017-07-09T12:34:56Z")) .build(); Unmarshaller unmarshaller = new Unmarshaller(); TestBean bean = new TestBean(); // Exercise unmarshaller.unmarshalToObject(entity, bean); // Verify Assert.assertEquals( OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant(), (Instant)bean.object); Assert.assertEquals( OffsetDateTime.parse("2017-07-09T12:34:56Z").toEpochSecond(), bean.primitiveLong); Assert.assertEquals( Long.valueOf(OffsetDateTime.parse("2017-07-09T12:34:56Z").toEpochSecond()), bean.boxedLong); Assert.assertEquals( Date.from(OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant()), bean.date); Assert.assertEquals( new Calendar.Builder() .setInstant(Date.from(OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant())) .build(), bean.calendar); Assert.assertEquals( java.sql.Timestamp.from(OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant()), bean.sqlTimestamp); Assert.assertEquals( OffsetDateTime.parse("2017-07-09T12:34:56Z") .atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime(), bean.localDateTime); Assert.assertEquals( OffsetDateTime.parse("2017-07-09T12:34:56Z"), bean.offsetDateTime); Assert.assertEquals( ZonedDateTime.parse("2017-07-09T12:34:56Z"), bean.zonedDateTime); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1294"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.github.davidmoten.fsm.runtime.rx; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import com.github.davidmoten.fsm.runtime.CancelTimedSignal; import com.github.davidmoten.fsm.runtime.Clock; import com.github.davidmoten.fsm.runtime.EntityBehaviour; import com.github.davidmoten.fsm.runtime.EntityStateMachine; import com.github.davidmoten.fsm.runtime.Event; import com.github.davidmoten.fsm.runtime.ObjectState; import com.github.davidmoten.fsm.runtime.Search; import com.github.davidmoten.fsm.runtime.Signal; import com.github.davidmoten.guavamini.Preconditions; import com.github.davidmoten.rx.Transformers; import rx.Observable; import rx.Observable.Transformer; import rx.Observer; import rx.Scheduler; import rx.Scheduler.Worker; import rx.Subscription; import rx.functions.Action1; import rx.functions.Func1; import rx.observables.GroupedObservable; import rx.observables.SyncOnSubscribe; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; public final class Processor<Id> { private final Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory; private final PublishSubject<Signal<?, Id>> subject; private final Scheduler signalScheduler; private final Scheduler processingScheduler; private final Map<ClassId<?, Id>, EntityStateMachine<?, Id>> stateMachines = new ConcurrentHashMap<>(); private final Map<ClassIdPair<Id>, Subscription> subscriptions = new ConcurrentHashMap<>(); private final Observable<Signal<?, Id>> signals; private final Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform; private final Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy; private final Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory; // nullable private final Clock signallerClock; private final Search<Id> search = new Search<Id>() { @Override public <T> Optional<T> search(Class<T> cls, Id id) { return getStateMachine(cls, id).get(); } }; private Processor(Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory, Scheduler processingScheduler, Scheduler signalScheduler, Observable<Signal<?, Id>> signals, Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform, Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy, Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory) { Preconditions.checkNotNull(behaviourFactory); Preconditions.checkNotNull(signalScheduler); Preconditions.checkNotNull(signals); Preconditions.checkNotNull(entityTransform); Preconditions.checkNotNull(preGroupBy); // mapFactory is nullable this.behaviourFactory = behaviourFactory; this.signalScheduler = signalScheduler; this.processingScheduler = processingScheduler; this.subject = PublishSubject.create(); this.signals = signals; this.entityTransform = entityTransform; this.preGroupBy = preGroupBy; this.mapFactory = mapFactory; this.signallerClock = Clock.from(signalScheduler); } public static <Id> Builder<Id> behaviourFactory( Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory) { return new Builder<Id>().behaviourFactory(behaviourFactory); } public static <T, Id> Builder<Id> behaviour(Class<T> cls, EntityBehaviour<T, Id> behaviour) { return new Builder<Id>().behaviour(cls, behaviour); } public static <Id> Builder<Id> signalScheduler(Scheduler signalScheduler) { return new Builder<Id>().signalScheduler(signalScheduler); } public static <Id> Builder<Id> processingScheduler(Scheduler processingScheduler) { return new Builder<Id>().processingScheduler(processingScheduler); } public static class Builder<Id> { private Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory; private Scheduler signalScheduler = Schedulers.computation(); private Scheduler processingScheduler = Schedulers.immediate(); private Observable<Signal<?, Id>> signals = Observable.empty(); private Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform = g -> g; private Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy = x -> x; private Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory; // nullable private final Map<Class<?>, EntityBehaviour<?, Id>> behaviours = new HashMap<>(); private Builder() { } public <T> Builder<Id> behaviour(Class<T> cls, EntityBehaviour<T, Id> behaviour) { behaviours.put(cls, behaviour); return this; } public Builder<Id> behaviourFactory( Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory) { this.behaviourFactory = behaviourFactory; return this; } public Builder<Id> signalScheduler(Scheduler signalScheduler) { this.signalScheduler = signalScheduler; return this; } public Builder<Id> processingScheduler(Scheduler processingScheduler) { this.processingScheduler = processingScheduler; return this; } public Builder<Id> signals(Observable<Signal<?, Id>> signals) { this.signals = signals; return this; } public Builder<Id> entityTransform( Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform) { this.entityTransform = entityTransform; return this; } public Builder<Id> preGroupBy(Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy) { this.preGroupBy = preGroupBy; return this; } public Builder<Id> mapFactory( Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory) { this.mapFactory = mapFactory; return this; } public Processor<Id> build() { Preconditions.checkArgument(behaviourFactory != null || !behaviours.isEmpty(), "one of behaviourFactory or multiple calls to behaviour must be made (behaviour must be specified)"); Preconditions.checkArgument(behaviourFactory == null || behaviours.isEmpty(), "cannot specify both behaviourFactory and behaviour"); if (!behaviours.isEmpty()) { behaviourFactory = cls -> behaviours.get(cls); } return new Processor<Id>(behaviourFactory, processingScheduler, signalScheduler, signals, entityTransform, preGroupBy, mapFactory); } } public Observable<EntityStateMachine<?, Id>> observable() { return Observable.defer(() -> { Worker worker = signalScheduler.createWorker(); @SuppressWarnings({ "unchecked", "rawtypes" }) Observable<GroupedObservable<ClassId<?, Id>, Signal<?, Id>>> o1 = subject .toSerialized() .onBackpressureBuffer() .mergeWith(signals) .doOnUnsubscribe(() -> worker.unsubscribe()) .compose(preGroupBy) .compose(Transformers .<Signal<?, Id>, ClassId<?, Id>, Signal<?, Id>> groupByEvicting( signal -> new ClassId(signal.cls(), signal.id()), x -> x, mapFactory)); return o1.flatMap(g -> { Observable<EntityStateMachine<?, Id>> obs = g .flatMap(processLambda(worker, g)) .doOnNext(m -> stateMachines.put(g.getKey(), m)) .subscribeOn(processingScheduler); return entityTransform.call(GroupedObservable.from(g.getKey(), obs)); }); }); } private Func1<? super Signal<?, Id>, Observable<EntityStateMachine<?, Id>>> processLambda( Worker worker, GroupedObservable<ClassId<?, Id>, Signal<?, Id>> g) { return x -> process(g.getKey(), x.event(), worker); } private static final class Signals<Id> { final Deque<Event<?>> signalsToSelf = new ArrayDeque<>(); final Deque<Signal<?, Id>> signalsToOther = new ArrayDeque<>(); } private Observable<EntityStateMachine<?, Id>> process(ClassId<?, Id> cid, Event<?> x, Worker worker) { return Observable.create(new SyncOnSubscribe<Signals<Id>, EntityStateMachine<?, Id>>() { @Override protected Signals<Id> generateState() { Signals<Id> signals = new Signals<>(); signals.signalsToSelf.offerFirst(x); return signals; } @Override protected Signals<Id> next(Signals<Id> signals, Observer<? super EntityStateMachine<?, Id>> observer) { @SuppressWarnings("unchecked") EntityStateMachine<Object, Id> m = (EntityStateMachine<Object, Id>) getStateMachine( cid.cls(), cid.id()); @SuppressWarnings("unchecked") Event<Object> event = (Event<Object>) signals.signalsToSelf.pollLast(); if (event != null) { applySignalToSelf(signals, observer, m, event); } else { applySignalsToOthers(cid, worker, signals); observer.onCompleted(); } return signals; } @SuppressWarnings("unchecked") private <T> void applySignalToSelf(Signals<Id> signals, Observer<? super EntityStateMachine<?, Id>> observer, EntityStateMachine<T, Id> m, Event<T> event) { m = m.signal(event); // stateMachines.put(id, m); observer.onNext(m); List<Event<? super T>> list = m.signalsToSelf(); for (int i = list.size() - 1; i >= 0; i signals.signalsToSelf.offerLast(list.get(i)); } for (Signal<?, ?> signal : m.signalsToOther()) { signals.signalsToOther.offerFirst((Signal<?, Id>) signal); } } private void applySignalsToOthers(ClassId<?, Id> cid, Worker worker, Signals<Id> signals) { Signal<?, Id> signal; while ((signal = signals.signalsToOther.pollLast()) != null) { Signal<?, Id> s = signal; if (signal.isImmediate()) { subject.onNext(signal); } else if (signal.event() instanceof CancelTimedSignal) { cancel(signal); } else { long delayMs = signal.time().get() - worker.now(); if (delayMs <= 0) { subject.onNext(signal); } else { scheduleSignal(cid, worker, signal, s, delayMs); } } } } private void cancel(Signal<?, Id> signal) { @SuppressWarnings("unchecked") CancelTimedSignal<Id> s = ((CancelTimedSignal<Id>) signal.event()); @SuppressWarnings({ "unchecked", "rawtypes" }) Subscription sub = subscriptions .remove(new ClassIdPair<Id>(new ClassId(s.fromClass(), s.fromId()), new ClassId(signal.cls(), signal.id()))); if (sub != null) { sub.unsubscribe(); } } private void scheduleSignal(ClassId<?, Id> from, Worker worker, Signal<?, Id> signal, Signal<?, Id> s, long delayMs) { // record pairwise signal so we can cancel it if // desired @SuppressWarnings({ "unchecked", "rawtypes" }) ClassIdPair<Id> idPair = new ClassIdPair<Id>(from, new ClassId(signal.cls(), signal.id())); long t1 = signalScheduler.now(); Subscription subscription = worker.schedule(() -> { subject.onNext(s.now()); } , delayMs, TimeUnit.MILLISECONDS); long t2 = signalScheduler.now(); worker.schedule(() -> { subscriptions.remove(idPair); } , delayMs - (t2 - t1), TimeUnit.MILLISECONDS); Subscription previous = subscriptions.put(idPair, subscription); if (previous != null) { previous.unsubscribe(); } } }); } @SuppressWarnings("unchecked") private <T> EntityStateMachine<T, Id> getStateMachine(Class<T> cls, Id id) { return (EntityStateMachine<T, Id>) stateMachines .computeIfAbsent(new ClassId<T, Id>(cls, id), clsId -> (EntityStateMachine<T, Id>) behaviourFactory.call(cls) .create(id) .withSearch(search) .withClock(signallerClock)); } public <T> Optional<T> getObject(Class<T> cls, Id id) { return getStateMachine(cls, id).get(); } public void signal(Signal<?, Id> signal) { subject.onNext(signal); } public <T> void signal(Class<T> cls, Id id, Event<? super T> event) { subject.onNext(Signal.create(cls, id, event)); } public <T> void signal(ClassId<T, Id> cid, Event<? super T> event) { signal(cid.cls(), cid.id(), event); } @SuppressWarnings("unchecked") public <T> ObjectState<T> get(Class<T> cls, Id id) { return (EntityStateMachine<T, Id>) stateMachines.get(new ClassId<T, Id>(cls, id)); } public void onCompleted() { subject.onCompleted(); } public void cancelSignal(Class<?> fromClass, Id fromId, Class<?> toClass, Id toId) { @SuppressWarnings({ "unchecked", "rawtypes" }) Subscription subscription = subscriptions.remove( new ClassIdPair<Id>(new ClassId(fromClass, fromId), new ClassId(toClass, toId))); if (subscription != null) { subscription.unsubscribe(); } } public void cancelSignalToSelf(Class<?> cls, Id id) { cancelSignal(cls, id, cls, id); } public void cancelSignalToSelf(ClassId<?, Id> cid) { cancelSignalToSelf(cid.cls(), cid.id()); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1295"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.github.davidmoten.fsm.runtime.rx; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import com.github.davidmoten.fsm.runtime.CancelTimedSignal; import com.github.davidmoten.fsm.runtime.EntityStateMachine; import com.github.davidmoten.fsm.runtime.Event; import com.github.davidmoten.fsm.runtime.ObjectState; import com.github.davidmoten.fsm.runtime.Signal; import com.github.davidmoten.guavamini.Preconditions; import rx.Observable; import rx.Observer; import rx.Scheduler; import rx.Scheduler.Worker; import rx.Subscription; import rx.functions.Func2; import rx.observables.SyncOnSubscribe; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; public final class Processor<Id> { private final Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory; private final PublishSubject<Signal<?, Id, ?>> subject; private final Scheduler signalScheduler; private final Scheduler processingScheduler; private final Map<ClassId<?>, EntityStateMachine<?>> stateMachines = new ConcurrentHashMap<>(); private final Map<ClassIdPair<Id>, Subscription> subscriptions = new ConcurrentHashMap<>(); private Processor(Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory, Scheduler processingScheduler, Scheduler signalScheduler) { Preconditions.checkNotNull(stateMachineFactory); Preconditions.checkNotNull(signalScheduler); this.stateMachineFactory = stateMachineFactory; this.signalScheduler = signalScheduler; this.processingScheduler = processingScheduler; this.subject = PublishSubject.create(); } public static <Id> Builder<Id> stateMachineFactory( Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory) { return new Builder<Id>().stateMachineFactory(stateMachineFactory); } public static <Id> Builder<Id> signalScheduler(Scheduler signalScheduler) { return new Builder<Id>().signalScheduler(signalScheduler); } public static <Id> Builder<Id> processingScheduler(Scheduler processingScheduler) { return new Builder<Id>().processingScheduler(processingScheduler); } public static class Builder<Id> { private Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory; private Scheduler signalScheduler = Schedulers.computation(); private Scheduler processingScheduler = Schedulers.immediate(); private Builder() { } public Builder<Id> stateMachineFactory( Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory) { this.stateMachineFactory = stateMachineFactory; return this; } public Builder<Id> signalScheduler(Scheduler signalScheduler) { this.signalScheduler = signalScheduler; return this; } public Builder<Id> processingScheduler(Scheduler processingScheduler) { this.processingScheduler = processingScheduler; return this; } public Processor<Id> build() { return new Processor<Id>(stateMachineFactory, processingScheduler, signalScheduler); } } public Observable<EntityStateMachine<?>> observable() { return Observable.defer(() -> { Worker worker = signalScheduler.createWorker(); return subject .toSerialized() .doOnUnsubscribe(() -> worker.unsubscribe()) .groupBy(signal -> new ClassId<Id>(signal.cls(), signal.id())) .flatMap(g -> g .flatMap(x -> process(g.getKey(), x.event(), worker)) .doOnNext(m -> stateMachines.put(g.getKey(), m)) .subscribeOn(processingScheduler)); }); } private static final class Signals<Id> { final Deque<Event<?>> signalsToSelf = new ArrayDeque<>(); final Deque<Signal<?, Id, ?>> signalsToOther = new ArrayDeque<>(); } private Observable<EntityStateMachine<?>> process(ClassId<Id> cid, Event<?> x, Worker worker) { return Observable.create(new SyncOnSubscribe<Signals<Id>, EntityStateMachine<?>>() { @Override protected Signals<Id> generateState() { Signals<Id> signals = new Signals<>(); signals.signalsToSelf.offerFirst(x); return signals; } @Override protected Signals<Id> next(Signals<Id> signals, Observer<? super EntityStateMachine<?>> observer) { EntityStateMachine<?> m = getStateMachine(cid.cls(), cid.id()); Event<?> event = signals.signalsToSelf.pollLast(); if (event != null) { applySignalToSelf(signals, observer, m, event); } else { applySignalsToOthers(cid, worker, signals); observer.onCompleted(); } return signals; } @SuppressWarnings("unchecked") private void applySignalToSelf(Signals<Id> signals, Observer<? super EntityStateMachine<?>> observer, EntityStateMachine<?> m, Event<?> event) { m = m.signal(event); // stateMachines.put(id, m); observer.onNext(m); List<Event<?>> list = m.signalsToSelf(); for (int i = list.size() - 1; i >= 0; i signals.signalsToSelf.offerLast(list.get(i)); } for (Signal<?, ?, ?> signal : m.signalsToOther()) { signals.signalsToOther.offerFirst((Signal<?, Id, ?>) signal); } } private void applySignalsToOthers(ClassId<Id> cid, Worker worker, Signals<Id> signals) { Signal<?, Id, ?> signal; while ((signal = signals.signalsToOther.pollLast()) != null) { Signal<?, Id, ?> s = signal; if (signal.isImmediate()) { subject.onNext(signal); } else if (signal.event() instanceof CancelTimedSignal) { cancel(signal); } else { long delayMs = signal.time() - worker.now(); if (delayMs <= 0) { subject.onNext(signal); } else { scheduleSignal(cid, worker, signal, s, delayMs); } } } } private void cancel(Signal<?, Id, ?> signal) { @SuppressWarnings("unchecked") CancelTimedSignal<Id> s = ((CancelTimedSignal<Id>) signal.event()); Subscription sub = subscriptions .remove(new ClassIdPair<Id>(new ClassId<Id>(s.fromClass(), s.fromId()), new ClassId<Id>(signal.cls(), signal.id()))); if (sub != null) { sub.unsubscribe(); } } private void scheduleSignal(ClassId<Id> from, Worker worker, Signal<?, Id, ?> signal, Signal<?, Id, ?> s, long delayMs) { // record pairwise signal so we can cancel it if // desired ClassIdPair<Id> idPair = new ClassIdPair<Id>(from, new ClassId<Id>(signal.cls(), signal.id())); long t1 = signalScheduler.now(); Subscription subscription = worker.schedule(() -> { subject.onNext(s.now()); } , delayMs, TimeUnit.MILLISECONDS); long t2 = signalScheduler.now(); worker.schedule(() -> { subscriptions.remove(idPair); } , delayMs - (t2 - t1), TimeUnit.MILLISECONDS); Subscription previous = subscriptions.put(idPair, subscription); if (previous != null) { previous.unsubscribe(); } } }); } @SuppressWarnings("unchecked") private <T> EntityStateMachine<T> getStateMachine(Class<T> cls, Id id) { EntityStateMachine<T> m = (EntityStateMachine<T>) stateMachines .get(new ClassId<Id>(cls, id)); if (m == null) { m = (EntityStateMachine<T>) stateMachineFactory.call(cls, id); } return m; } public <T> Optional<T> getObject(Class<T> cls, Id id) { return getStateMachine(cls, id).get(); } public void signal(Signal<?, Id, ?> signal) { subject.onNext(signal); } public <T, R> void signal(Class<T> cls, Id id, Event<R> event) { subject.onNext(Signal.create(cls, id, event)); } public <T> void signal(ClassId<Id> cid, Event<T> event) { subject.onNext(Signal.create(cid.cls(), cid.id(), event)); } @SuppressWarnings("unchecked") public <T> ObjectState<T> get(Class<T> cls, Id id) { return (EntityStateMachine<T>) stateMachines.get(new ClassId<Id>(cls, id)); } public void onCompleted() { subject.onCompleted(); } public void cancelSignal(Class<?> fromClass, Id fromId, Class<?> toClass, Id toId) { Subscription subscription = subscriptions.remove(new ClassIdPair<Id>( new ClassId<Id>(fromClass, fromId), new ClassId<Id>(toClass, toId))); if (subscription != null) { subscription.unsubscribe(); } } public void cancelSignalToSelf(Class<?> cls, Id id) { cancelSignal(cls, id, cls, id); } public void cancelSignalToSelf(ClassId<Id> cid) { cancelSignalToSelf(cid.cls(), cid.id()); } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1296"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.emc.mongoose.storage.mock.impl.base; import com.emc.mongoose.common.collection.ListingLRUMap; import com.emc.mongoose.common.concurrent.BlockingQueueTaskSequencer; import com.emc.mongoose.common.concurrent.FutureTaskBase; import com.emc.mongoose.model.api.data.ContentSource; import com.emc.mongoose.model.impl.item.CsvFileItemInput; import com.emc.mongoose.storage.mock.api.MutableDataItemMock; import com.emc.mongoose.storage.mock.api.ObjectContainerMock; import com.emc.mongoose.storage.mock.api.StorageIoStats; import com.emc.mongoose.storage.mock.api.StorageMock; import com.emc.mongoose.storage.mock.api.exception.ContainerMockException; import com.emc.mongoose.storage.mock.api.exception.ContainerMockNotFoundException; import com.emc.mongoose.storage.mock.api.exception.ObjectMockNotFoundException; import com.emc.mongoose.storage.mock.api.exception.StorageMockCapacityLimitReachedException; import com.emc.mongoose.ui.config.Config; import com.emc.mongoose.ui.log.LogUtil; import com.emc.mongoose.ui.log.Markers; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.EOFException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; public abstract class StorageMockBase<T extends MutableDataItemMock> implements StorageMock<T> { private static final Logger LOG = LogManager.getLogger(); private final AtomicBoolean started = new AtomicBoolean(false); private final String dataSrcPath; private final StorageIoStats ioStats; protected final ContentSource contentSrc; private final int storageCapacity, containerCapacity; private final ListingLRUMap<String, ObjectContainerMock<T>> storageMap; private final ObjectContainerMock<T> defaultContainer; private volatile boolean isCapacityExhausted = false; @SuppressWarnings("unchecked") public StorageMockBase( final Config.StorageConfig.MockConfig mockConfig, final Config.LoadConfig.MetricsConfig metricsConfig, final Config.ItemConfig itemConfig, final ContentSource contentSrc ) { super(); final Config.StorageConfig.MockConfig.ContainerConfig containerConfig = mockConfig.getContainerConfig(); storageMap = new ListingLRUMap<>(containerConfig.getCountLimit()); this.dataSrcPath = itemConfig.getInputConfig().getFile(); this.contentSrc = contentSrc; this.ioStats = new BasicStorageIoStats(this, (int) metricsConfig.getPeriod()); this.storageCapacity = mockConfig.getCapacity(); this.containerCapacity = containerConfig.getCapacity(); this.defaultContainer = new BasicObjectContainerMock<>(containerCapacity); storageMap.put(getClass().getSimpleName().toLowerCase(), defaultContainer); } // Container methods @Override public final void createContainer(final String name) { synchronized(storageMap) { storageMap.put(name, new BasicObjectContainerMock<>(containerCapacity)); ioStats.containerCreate(); } } @Override public final ObjectContainerMock<T> getContainer(final String name) { synchronized(storageMap) { return storageMap.get(name); } } @Override public final void deleteContainer(final String name) { synchronized(storageMap) { storageMap.remove(name); ioStats.containerDelete(); } } // Object methods protected abstract T newDataObject(final String id, final long offset, final long size); @Override public final void createObject( final String containerName, final String id, final long offset, final long size ) throws ContainerMockNotFoundException, StorageMockCapacityLimitReachedException { if(isCapacityExhausted) { throw new StorageMockCapacityLimitReachedException(); } final ObjectContainerMock<T> c = getContainer(containerName); if(c != null) { c.put(id, newDataObject(id, offset, size)); } else { throw new ContainerMockNotFoundException(containerName); } } @Override public final void updateObject( final String containerName, final String id, final long offset, final long size ) throws ContainerMockException, ObjectMockNotFoundException { final ObjectContainerMock<T> c = getContainer(containerName); if(c != null) { final T obj = c.get(id); if(obj != null) { obj.update(offset, size); } else { throw new ObjectMockNotFoundException(id); } } else { throw new ContainerMockNotFoundException(containerName); } } @Override public final void appendObject( final String containerName, final String id, final long offset, final long size ) throws ContainerMockException, ObjectMockNotFoundException { final ObjectContainerMock<T> c = getContainer(containerName); if(c != null) { final T obj = c.get(id); if(obj != null) { obj.append(offset, size); } else { throw new ObjectMockNotFoundException(id); } } else { throw new ContainerMockNotFoundException(containerName); } } @Override public final T getObject( final String containerName, final String id, final long offset, final long size ) throws ContainerMockException { // TODO partial read using offset and size args final ObjectContainerMock<T> c = getContainer(containerName); if(c != null) { return c.get(id); } else { throw new ContainerMockNotFoundException(containerName); } } @Override public final void deleteObject( final String containerName, final String id, final long offset, final long size ) throws ContainerMockNotFoundException { final ObjectContainerMock<T> c = getContainer(containerName); if(c != null) { c.remove(id); } else { throw new ContainerMockNotFoundException(containerName); } } @Override public final T listObjects( final String containerName, final String afterObjectId, final Collection<T> outputBuffer, final int limit ) throws ContainerMockException { final ObjectContainerMock<T> container = getContainer(containerName); if(container != null) { return container.list(afterObjectId, outputBuffer, limit); } else { throw new ContainerMockNotFoundException(containerName); } } private final Thread storageCapacityMonitorThread = new Thread("storageMockCapacityMonitor") { { setDaemon(true); } @SuppressWarnings("InfiniteLoopStatement") @Override public final void run() { long currObjCount; try { while(true) { TimeUnit.SECONDS.sleep(1); currObjCount = getSize(); if(!isCapacityExhausted && currObjCount > storageCapacity) { isCapacityExhausted = true; } else if(isCapacityExhausted && currObjCount <= storageCapacity) { isCapacityExhausted = false; } } } catch(final InterruptedException ignored) { } } }; @Override public final void start() { loadPersistedDataItems(); ioStats.start(); doStart(); storageCapacityMonitorThread.start(); started.set(true); } @Override public final boolean isStarted() { return started.get(); } protected abstract void doStart(); @Override public long getSize() { long size = 0; synchronized(storageMap) { for(final ObjectContainerMock<T> container : storageMap.values()) { size += container.size(); } } return size; } @Override public long getCapacity() { return storageCapacity; } @Override public final void putIntoDefaultContainer(final List<T> dataItems) { for(final T object : dataItems) { defaultContainer.put(object.getName(), object); } } @Override public StorageIoStats getStats() { return ioStats; } @SuppressWarnings({"InfiniteLoopStatement", "unchecked"}) private void loadPersistedDataItems() { if(dataSrcPath != null && !dataSrcPath.isEmpty()) { final Path dataFilePath = Paths.get(dataSrcPath); if(!Files.exists(dataFilePath)) { LOG.warn( Markers.ERR, "Data item source file @ \"" + dataSrcPath + "\" doesn't exists" ); return; } if(Files.isDirectory(dataFilePath)) { LOG.warn( Markers.ERR, "Data item source file @ \"" + dataSrcPath + "\" is a directory" ); return; } if(Files.isReadable(dataFilePath)) { LOG.debug( Markers.ERR, "Data item source file @ \"" + dataSrcPath + "\" is not readable" ); } final AtomicLong count = new AtomicLong(0); List<T> buff; int n; final Thread displayProgressThread = new Thread(() -> { try { while(true) { LOG.info(Markers.MSG, "{} items loaded...", count.get()); TimeUnit.SECONDS.sleep(10); } } catch(final InterruptedException ignored) { } }); try( final CsvFileItemInput<T> csvFileItemInput = new CsvFileItemInput<>( dataFilePath, (Class<T>) BasicMutableDataItemMock.class, contentSrc ) ) { displayProgressThread.start(); do { buff = new ArrayList<>(4096); n = csvFileItemInput.get(buff, 4096); if(n > 0) { putIntoDefaultContainer(buff); count.addAndGet(n); } else { break; } } while(true); } catch(final EOFException e) { LOG.info(Markers.MSG, "Loaded {} data items from file {}", count, dataFilePath); } catch(final IOException | NoSuchMethodException e) { LogUtil.exception( LOG, Level.WARN, e, "Failed to load the data items from file \"{}\"", dataFilePath ); } finally { displayProgressThread.interrupt(); } } } private abstract class ContainerTaskBase extends FutureTaskBase<T> { private final String containerName; public ContainerTaskBase(final String containerName) { this.containerName = containerName; } public ObjectContainerMock<T> getContainer() { return storageMap.get(containerName); } protected final boolean setException() { return setException( new ContainerMockNotFoundException(containerName) ); } } private final class PutObjectsBatchTask extends FutureTaskBase<List<T>> { private final String containerName; private final List<T> objects; public PutObjectsBatchTask(final String containerName, final List<T> objects) { this.containerName = containerName; this.objects = objects; } @Override public final void run() { final ObjectContainerMock<T> container = storageMap.get(containerName); if(container != null) { objects.forEach(object -> container.put(object.getName(), object)); set(new ArrayList<>(container.values())); } else { setException(new ContainerMockNotFoundException(containerName)); } } } private final class ListObjectsTask extends ContainerTaskBase { private final String afterObjectId; private final Collection<T> outputBuffer; private final int limit; public ListObjectsTask( final String containerName, final String afterObjectId, final Collection<T> outputBuffer, final int limit ) { super(containerName); this.afterObjectId = afterObjectId; this.outputBuffer = outputBuffer; this.limit = limit; } @Override public final void run() { final ObjectContainerMock<T> container = getContainer(); if(container != null) { set(container.list(afterObjectId, outputBuffer, limit)); } else { setException(); } } } private final class DeleteObjectTask extends ContainerTaskBase { private final String objectId; public DeleteObjectTask(final String containerName, final String objectId) { super(containerName); this.objectId = objectId; } @Override public final void run() { final ObjectContainerMock<T> container = getContainer(); if(container != null) { set(container.remove(objectId)); } else { setException(); } } } private final class GetObjectTask extends ContainerTaskBase { private final String objectId; public GetObjectTask(final String containerName, final String objectId) { super(containerName); this.objectId = objectId; } @Override public final void run() { final ObjectContainerMock<T> container = getContainer(); if(container != null) { set(container.get(objectId)); } else { setException(); } } } private final class PutObjectTask extends ContainerTaskBase { private T object; public PutObjectTask(final String containerName, final T object) { super(containerName); this.object = object; } @Override public final void run() { final ObjectContainerMock<T> container = getContainer(); if(container != null) { set(container.put(object.getName(), object)); } else { setException(); } } } private final class DeleteContainerTask extends FutureTaskBase<ObjectContainerMock<T>> { private final String containerName; public DeleteContainerTask(final String containerName) { this.containerName = containerName; } @Override public final void run() { if(storageMap.containsKey(containerName)) { set(storageMap.remove(containerName)); } else { setException(new ContainerMockNotFoundException(containerName)); } } } private final class GetContainerTask extends FutureTaskBase<ObjectContainerMock<T>> { private final String containerName; public GetContainerTask(final String containerName) { this.containerName = containerName; } @Override public final void run() { if(storageMap.containsKey(containerName)) { set(storageMap.get(containerName)); } else { setException(new ContainerMockNotFoundException(containerName)); } } } private final class PutContainerTask extends FutureTaskBase<ObjectContainerMock<T>> { private final String containerName; public PutContainerTask(final String containerName) { this.containerName = containerName; } @Override public final void run() { set(storageMap.put(containerName, new BasicObjectContainerMock<>(containerCapacity))); ioStats.containerCreate(); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1297"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.duracloud.swiftstorage; import static org.duracloud.common.error.RetryFlaggableException.NO_RETRY; import static org.duracloud.common.error.RetryFlaggableException.RETRY; import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_CHECKSUM; import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_MD5; import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_MIMETYPE; import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_MODIFIED; import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_SIZE; import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_SPACE_COUNT; import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_SPACE_CREATED; import java.lang.reflect.Field; import java.util.Date; import java.util.HashMap; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.Headers; import com.amazonaws.services.s3.model.AccessControlList; import com.amazonaws.services.s3.model.AmazonS3Exception; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.CopyObjectRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import org.apache.commons.lang.StringUtils; import org.duracloud.common.constant.Constants; import org.duracloud.common.rest.HttpHeaders; import org.duracloud.s3storage.S3ProviderUtil; import org.duracloud.s3storage.S3StorageProvider; import org.duracloud.storage.domain.StorageProviderType; import org.duracloud.storage.error.NotFoundException; import org.duracloud.storage.error.StorageException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SwiftStorageProvider extends S3StorageProvider { private final Logger log = LoggerFactory.getLogger(SwiftStorageProvider.class); public SwiftStorageProvider(String accessKey, String secretKey, Map<String, String> options) { super(accessKey, secretKey, options); } public SwiftStorageProvider(AmazonS3 s3Client, String accessKey) { super(s3Client, accessKey, null); } private static String[] SWIFT_METADATA_LIST = {Headers.ETAG, Headers.CONTENT_LENGTH, Headers.DATE, Headers.LAST_MODIFIED, Headers.CONTENT_TYPE}; /** * {@inheritDoc} */ @Override public StorageProviderType getStorageProviderType() { return StorageProviderType.SWIFT_S3; } @Override protected Bucket createBucket(String spaceId) { String bucketName = getNewBucketName(spaceId); try { Bucket bucket = s3Client.createBucket(bucketName); // Swift has no concept of bucket lifecycle return bucket; } catch (AmazonClientException e) { String err = "Could not create Swift container with name " + bucketName + " due to error: " + e.getMessage(); throw new StorageException(err, e, RETRY); } } @Override public void removeSpace(String spaceId) { // Will throw if bucket does not exist String bucketName = getBucketName(spaceId); String propertiesBucketName = getBucketName(PROPERTIES_BUCKET); try { s3Client.deleteBucket(bucketName); } catch (AmazonClientException e) { String err = "Could not delete Swift container with name " + bucketName + " due to error: " + e.getMessage(); throw new StorageException(err, e, RETRY); } // Space properties are stored as tags with the S3 bucket. // So with Swift we need to delete the associated properties object in Swift. s3Client.deleteObject(propertiesBucketName, spaceId); } @Override public String createHiddenSpace(String spaceId, int expirationInDays) { String bucketName = getHiddenBucketName(spaceId); try { Bucket bucket = s3Client.createBucket(bucketName); return spaceId; } catch (AmazonClientException e) { String err = "Could not create Swift container with name " + bucketName + " due to error: " + e.getMessage(); throw new StorageException(err, e, RETRY); } } // Swift access keys are longer than 20 characters, and creating // a bucket starting with your access key causes problems. @Override protected String getNewBucketName(String spaceId) { String truncatedKey = truncateKey(accessKeyId); return S3ProviderUtil.createNewBucketName(truncatedKey, spaceId); } @Override protected String getSpaceId(String bucketName) { String spaceId = bucketName; String truncatedKey = truncateKey(accessKeyId); if (isSpace(bucketName)) { spaceId = spaceId.substring(truncatedKey.length() + 1); } return spaceId; } @Override protected Map<String, String> getAllSpaceProperties(String spaceId) { log.debug("getAllSpaceProperties(" + spaceId + ")"); // Will throw if bucket does not exist String propsBucketName = getBucketName(PROPERTIES_BUCKET); Map<String, String> spaceProperties = new HashMap<>(); String spacePropertiesString; try { spacePropertiesString = s3Client.getObjectAsString(propsBucketName, spaceId); // Remove the {} from the string spacePropertiesString = spacePropertiesString.substring(1, spacePropertiesString.length() - 1); String[] spacePropertiesList = spacePropertiesString.split(", "); for (String property : spacePropertiesList) { String[] props = property.split("="); spaceProperties.put(props[0], props[1]); } } catch (AmazonS3Exception e) { // If no space properties have been set yet, then the object will not exist. // But we don't need to create it here, as it gets created when properties are set. log.debug( "Metadata object for space " + spaceId + " was not found in container " + propsBucketName + ", probably because this is a new space." ); } // Handle @ symbol (change from +), to allow for email usernames in ACLs spaceProperties = replaceInMapValues(spaceProperties, "+", "@"); // Add space count spaceProperties.put(PROPERTIES_SPACE_COUNT, getSpaceCount(spaceId, MAX_ITEM_COUNT)); return spaceProperties; } @Override protected void doSetSpaceProperties(String spaceId, Map<String, String> spaceProperties) { log.debug("setSpaceProperties(" + spaceId + ")"); Map<String, String> originalProperties; try { originalProperties = getAllSpaceProperties(spaceId); } catch (NotFoundException e) { // The metadata bucket does not exist yet, so create it createHiddenSpace(PROPERTIES_BUCKET, 0); // And set the original properties to a new, empty HashMap originalProperties = new HashMap<>(); } // By calling this _after_ we have requested the space properties, // we ensure that the metadata bucket exists. String metadataBucketName = getBucketName(PROPERTIES_BUCKET); // Set creation date String creationDate = originalProperties.get(PROPERTIES_SPACE_CREATED); if (creationDate == null) { creationDate = spaceProperties.get(PROPERTIES_SPACE_CREATED); if (creationDate == null) { // getCreationDate() does not work properly on Swift creationDate = formattedDate(new Date()); } } spaceProperties.put(PROPERTIES_SPACE_CREATED, creationDate); // Handle @ symbol (change to +), to allow for email usernames in ACLs spaceProperties = replaceInMapValues(spaceProperties, "@", "+"); // Store properties in an object in the hidden metadata bucket log.debug( "Writing space properties " + spaceProperties.toString() + " to object " + spaceId + " in Swift container " + metadataBucketName ); s3Client.putObject(metadataBucketName, spaceId, spaceProperties.toString()); } @Override protected void updateObjectProperties(String bucketName, String contentId, ObjectMetadata objMetadata) { try { AccessControlList originalACL = s3Client.getObjectAcl(bucketName, contentId); CopyObjectRequest copyRequest = new CopyObjectRequest(bucketName, contentId, bucketName, contentId); copyRequest.setStorageClass(DEFAULT_STORAGE_CLASS); copyRequest.setNewObjectMetadata(objMetadata); // Setting object ACLs resets an object's ContentType to application/xml! // But setting the ACLs before we do the copy request gets around this. copyRequest.setAccessControlList(originalACL); s3Client.copyObject(copyRequest); } catch (AmazonClientException e) { throwIfContentNotExist(bucketName, contentId); String err = "Could not update metadata for content " + contentId + " in Swift container " + bucketName + " due to error: " + e.getMessage(); throw new StorageException(err, e, NO_RETRY); } } @Override protected Map<String, String> prepContentProperties(ObjectMetadata objMetadata) { Map<String, String> contentProperties = new HashMap<>(); // Set the user properties Map<String, String> userProperties = objMetadata.getUserMetadata(); for (String metaName : userProperties.keySet()) { String metaValue = userProperties.get(metaName); if (metaName.trim().equalsIgnoreCase("tags") || metaName.trim().equalsIgnoreCase("tags" + HEADER_KEY_SUFFIX) || metaName.trim().equalsIgnoreCase(PROPERTIES_CONTENT_MIMETYPE) || metaName.trim().equalsIgnoreCase(PROPERTIES_CONTENT_MIMETYPE + HEADER_KEY_SUFFIX)) { metaName = metaName.toLowerCase(); } contentProperties.put(getWithSpace(decodeHeaderKey(metaName)), decodeHeaderValue(metaValue)); } // Set the response metadata Map<String, Object> responseMeta = objMetadata.getRawMetadata(); for (String metaName : responseMeta.keySet()) { // Don't include Swift response headers try { if (!isSwiftMetadata(metaName)) { Object metaValue = responseMeta.get(metaName); // Remove extra Swift metadata from user properties section for (String swiftMetaName : SWIFT_METADATA_LIST) { if (metaName.trim().equalsIgnoreCase(swiftMetaName)) { metaName = swiftMetaName; } } contentProperties.put(metaName, String.valueOf(metaValue)); } } catch (IllegalArgumentException e) { e.printStackTrace(); } // Remove User Response headers that are also in RawMetadata // Swift metadata are non-standard HTTP headers so DuraCloud views them as "User" metadata if (userProperties.keySet() .contains(metaName + HEADER_KEY_SUFFIX) && contentProperties.containsKey(metaName)) { contentProperties.remove(metaName); } } // Set MIMETYPE String contentType = objMetadata.getContentType(); if (contentType != null) { contentProperties.put(PROPERTIES_CONTENT_MIMETYPE, contentType); contentProperties.put(Headers.CONTENT_TYPE, contentType); } // Set CONTENT_ENCODING String encoding = objMetadata.getContentEncoding(); if (encoding != null) { contentProperties.put(Headers.CONTENT_ENCODING, encoding); } // Set SIZE long contentLength = objMetadata.getContentLength(); if (contentLength >= 0) { String size = String.valueOf(contentLength); contentProperties.put(PROPERTIES_CONTENT_SIZE, size); contentProperties.put(Headers.CONTENT_LENGTH, size); } // Set CHECKSUM String checksum = objMetadata.getETag(); if (checksum != null) { String eTagValue = getETagValue(checksum); contentProperties.put(PROPERTIES_CONTENT_CHECKSUM, eTagValue); contentProperties.put(PROPERTIES_CONTENT_MD5, eTagValue); contentProperties.put(Headers.ETAG, eTagValue); } // Set MODIFIED Date modified = objMetadata.getLastModified(); if (modified != null) { String modDate = formattedDate(modified); contentProperties.put(PROPERTIES_CONTENT_MODIFIED, modDate); contentProperties.put(Headers.LAST_MODIFIED, modDate); } return contentProperties; } private String truncateKey(String accessKey) { // Convert access key to 20 character string return StringUtils.left(accessKey, 20); } private boolean isSwiftMetadata(String metaName) { Field[] httpFields = HttpHeaders.class.getFields(); for (Field f : httpFields) { String fieldName = null; try { fieldName = (String) f.get(httpFields); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } if (metaName.equalsIgnoreCase(fieldName)) { return false; } } return true; } /** * Add expire header for object in Swift. * @param bucketName * @param contentId * @param seconds */ public ObjectMetadata expireObject(String bucketName, String contentId, Integer seconds) { log.debug("Expiring object {} in {} after {} seconds.", contentId, bucketName, seconds); ObjectMetadata objMetadata = getObjectDetails(bucketName, contentId, true); objMetadata.setHeader(Constants.SWIFT_EXPIRE_OBJECT_HEADER, seconds); updateObjectProperties(bucketName, contentId, objMetadata); return objMetadata; } private ObjectMetadata getObjectDetails(String bucketName, String contentId, boolean retry) { try { return s3Client.getObjectMetadata(bucketName, contentId); } catch (AmazonClientException e) { throwIfContentNotExist(bucketName, contentId); String err = "Could not get details for content " + contentId + " in Swift container " + bucketName + " due to error: " + e.getMessage(); throw new StorageException(err, e, retry); } } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1298"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonProperty; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.games.Animation; import org.telegram.telegrambots.meta.api.objects.games.Game; import org.telegram.telegrambots.meta.api.objects.passport.PassportData; import org.telegram.telegrambots.meta.api.objects.payments.Invoice; import org.telegram.telegrambots.meta.api.objects.payments.SuccessfulPayment; import org.telegram.telegrambots.meta.api.objects.stickers.Sticker; import java.util.ArrayList; import java.util.List; /** * @author Ruben Bermudez * @version 1.0 * This object represents a message. */ public class Message implements BotApiObject { private static final String MESSAGEID_FIELD = "message_id"; private static final String FROM_FIELD = "from"; private static final String DATE_FIELD = "date"; private static final String CHAT_FIELD = "chat"; private static final String FORWARDFROM_FIELD = "forward_from"; private static final String FORWARDFROMCHAT_FIELD = "forward_from_chat"; private static final String FORWARDDATE_FIELD = "forward_date"; private static final String TEXT_FIELD = "text"; private static final String ENTITIES_FIELD = "entities"; private static final String CAPTIONENTITIES_FIELD = "caption_entities"; private static final String AUDIO_FIELD = "audio"; private static final String DOCUMENT_FIELD = "document"; private static final String PHOTO_FIELD = "photo"; private static final String STICKER_FIELD = "sticker"; private static final String VIDEO_FIELD = "video"; private static final String CONTACT_FIELD = "contact"; private static final String LOCATION_FIELD = "location"; private static final String VENUE_FIELD = "venue"; private static final String ANIMATION_FIELD = "animation"; private static final String PINNED_MESSAGE_FIELD = "pinned_message"; private static final String NEWCHATMEMBERS_FIELD = "new_chat_members"; private static final String LEFTCHATMEMBER_FIELD = "left_chat_member"; private static final String NEWCHATTITLE_FIELD = "new_chat_title"; private static final String NEWCHATPHOTO_FIELD = "new_chat_photo"; private static final String DELETECHATPHOTO_FIELD = "delete_chat_photo"; private static final String GROUPCHATCREATED_FIELD = "group_chat_created"; private static final String REPLYTOMESSAGE_FIELD = "reply_to_message"; private static final String VOICE_FIELD = "voice"; private static final String CAPTION_FIELD = "caption"; private static final String SUPERGROUPCREATED_FIELD = "supergroup_chat_created"; private static final String CHANNELCHATCREATED_FIELD = "channel_chat_created"; private static final String MIGRATETOCHAT_FIELD = "migrate_to_chat_id"; private static final String MIGRATEFROMCHAT_FIELD = "migrate_from_chat_id"; private static final String EDITDATE_FIELD = "edit_date"; private static final String GAME_FIELD = "game"; private static final String FORWARDFROMMESSAGEID_FIELD = "forward_from_message_id"; private static final String INVOICE_FIELD = "invoice"; private static final String SUCCESSFUL_PAYMENT_FIELD = "successful_payment"; private static final String VIDEO_NOTE_FIELD = "video_note"; private static final String AUTHORSIGNATURE_FIELD = "author_signature"; private static final String FORWARDSIGNATURE_FIELD = "forward_signature"; private static final String MEDIAGROUPID_FIELD = "media_group_id"; private static final String CONNECTEDWEBSITE_FIELD = "connected_website"; private static final String PASSPORTDATA_FIELD = "passport_data"; @JsonProperty(MESSAGEID_FIELD) private Integer messageId; ///< Integer Unique message identifier @JsonProperty(FROM_FIELD) private User from; ///< Optional. Sender, can be empty for messages sent to channels @JsonProperty(DATE_FIELD) private Integer date; ///< Optional. Date the message was sent in Unix time @JsonProperty(CHAT_FIELD) private Chat chat; ///< Conversation the message belongs to @JsonProperty(FORWARDFROM_FIELD) private User forwardFrom; ///< Optional. For forwarded messages, sender of the original message @JsonProperty(FORWARDFROMCHAT_FIELD) private Chat forwardFromChat; ///< Optional. For messages forwarded from a channel, information about the original channel @JsonProperty(FORWARDDATE_FIELD) private Integer forwardDate; ///< Optional. For forwarded messages, date the original message was sent @JsonProperty(TEXT_FIELD) private String text; ///< Optional. For text messages, the actual UTF-8 text of the message /** * Optional. For text messages, special entities like usernames, URLs, * bot commands, etc. that appear in the text */ @JsonProperty(ENTITIES_FIELD) private List<MessageEntity> entities; /** * Optional. For messages with a caption, special entities like usernames, * URLs, bot commands, etc. that appear in the caption */ @JsonProperty(CAPTIONENTITIES_FIELD) private List<MessageEntity> captionEntities; @JsonProperty(AUDIO_FIELD) private Audio audio; ///< Optional. Message is an audio file, information about the file @JsonProperty(DOCUMENT_FIELD) private Document document; ///< Optional. Message is a general file, information about the file @JsonProperty(PHOTO_FIELD) private List<PhotoSize> photo; ///< Optional. Message is a photo, available sizes of the photo @JsonProperty(STICKER_FIELD) private Sticker sticker; ///< Optional. Message is a sticker, information about the sticker @JsonProperty(VIDEO_FIELD) private Video video; ///< Optional. Message is a video, information about the video @JsonProperty(CONTACT_FIELD) private Contact contact; ///< Optional. Message is a shared contact, information about the contact @JsonProperty(LOCATION_FIELD) private Location location; ///< Optional. Message is a shared location, information about the location @JsonProperty(VENUE_FIELD) private Venue venue; ///< Optional. Message is a venue, information about the venue /** * Optional. Message is an animation, information about the animation. * For backward compatibility, when this field is set, the document field will be also set */ @JsonProperty(ANIMATION_FIELD) private Animation animation; @JsonProperty(PINNED_MESSAGE_FIELD) private Message pinnedMessage; ///< Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply. @JsonProperty(NEWCHATMEMBERS_FIELD) private List<User> newChatMembers; ///< Optional. New members were added to the group or supergroup, information about them (the bot itself may be one of these members) @JsonProperty(LEFTCHATMEMBER_FIELD) private User leftChatMember; ///< Optional. A member was removed from the group, information about them (this member may be bot itself) @JsonProperty(NEWCHATTITLE_FIELD) private String newChatTitle; ///< Optional. A chat title was changed to this value @JsonProperty(NEWCHATPHOTO_FIELD) private List<PhotoSize> newChatPhoto; ///< Optional. A chat photo was change to this value @JsonProperty(DELETECHATPHOTO_FIELD) private Boolean deleteChatPhoto; ///< Optional. Informs that the chat photo was deleted @JsonProperty(GROUPCHATCREATED_FIELD) private Boolean groupchatCreated; ///< Optional. Informs that the group has been created @JsonProperty(REPLYTOMESSAGE_FIELD) private Message replyToMessage; @JsonProperty(VOICE_FIELD) private Voice voice; ///< Optional. Message is a voice message, information about the file @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Caption for the document, photo or video, 0-200 characters @JsonProperty(SUPERGROUPCREATED_FIELD) private Boolean superGroupCreated; @JsonProperty(CHANNELCHATCREATED_FIELD) private Boolean channelChatCreated; /** * Optional. The group has been migrated to a supergroup with the specified identifier. * This number may be greater than 32 bits and some programming languages * may have difficulty/silent defects in interpreting it. * But it smaller than 52 bits, so a signed 64 bit integer or double-precision * float type are safe for storing this identifier. */ @JsonProperty(MIGRATETOCHAT_FIELD) private Long migrateToChatId; ///< Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value /** * Optional. The supergroup has been migrated from a group with the specified identifier. * This number may be greater than 32 bits and some programming languages * may have difficulty/silent defects in interpreting it. * But it smaller than 52 bits, so a signed 64 bit integer or double-precision * float type are safe for storing this identifier. */ @JsonProperty(MIGRATEFROMCHAT_FIELD) private Long migrateFromChatId; ///< Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value @JsonProperty(EDITDATE_FIELD) private Integer editDate; ///< Optional. Date the message was last edited in Unix time @JsonProperty(GAME_FIELD) private Game game; ///< Optional. Message is a game, information about the game @JsonProperty(FORWARDFROMMESSAGEID_FIELD) private Integer forwardFromMessageId; ///< Optional. For forwarded channel posts, identifier of the original message in the channel @JsonProperty(INVOICE_FIELD) private Invoice invoice; ///< Optional. Message is an invoice for a payment, information about the invoice. @JsonProperty(SUCCESSFUL_PAYMENT_FIELD) private SuccessfulPayment successfulPayment; ///< Optional. Message is a service message about a successful payment, information about the payment. @JsonProperty(VIDEO_NOTE_FIELD) private VideoNote videoNote; ///< Optional. Message is a video note, information about the video message @JsonProperty(AUTHORSIGNATURE_FIELD) private String authorSignature; ///< Optional. Post author signature for posts in channel chats @JsonProperty(FORWARDSIGNATURE_FIELD) private String forwardSignature; ///< Optional. Post author signature for messages forwarded from channel chats @JsonProperty(MEDIAGROUPID_FIELD) private String mediaGroupId; ///< Optional. The unique identifier of a media message group this message belongs to @JsonProperty(CONNECTEDWEBSITE_FIELD) private String connectedWebsite; ///< Optional. The domain name of the website on which the user has logged in @JsonProperty(PASSPORTDATA_FIELD) private PassportData passportData; ///< Optional. Telegram Passport data public Message() { super(); } public Integer getMessageId() { return messageId; } public User getFrom() { return from; } public Integer getDate() { return date; } public Chat getChat() { return chat; } public User getForwardFrom() { return forwardFrom; } public Integer getForwardDate() { return forwardDate; } public String getText() { return text; } public List<MessageEntity> getEntities() { if (entities != null) { entities.forEach(x -> x.computeText(text)); } return entities; } public List<MessageEntity> getCaptionEntities() { if (captionEntities != null) { captionEntities.forEach(x -> x.computeText(caption)); } return captionEntities; } public Audio getAudio() { return audio; } public Document getDocument() { return document; } public List<PhotoSize> getPhoto() { return photo; } public Sticker getSticker() { return sticker; } public boolean hasSticker() { return sticker != null; } public Video getVideo() { return video; } public Animation getAnimation() { return animation; } public Contact getContact() { return contact; } public Location getLocation() { return location; } public Venue getVenue() { return venue; } public Message getPinnedMessage() { return pinnedMessage; } public List<User> getNewChatMembers() { return newChatMembers == null ? new ArrayList<>() : newChatMembers; } public User getLeftChatMember() { return leftChatMember; } public String getNewChatTitle() { return newChatTitle; } public List<PhotoSize> getNewChatPhoto() { return newChatPhoto; } public Boolean getDeleteChatPhoto() { return deleteChatPhoto; } public Boolean getGroupchatCreated() { return groupchatCreated; } public Message getReplyToMessage() { return replyToMessage; } public Voice getVoice() { return voice; } public String getCaption() { return caption; } public Boolean getSuperGroupCreated() { return superGroupCreated; } public Boolean getChannelChatCreated() { return channelChatCreated; } public Long getMigrateToChatId() { return migrateToChatId; } public Long getMigrateFromChatId() { return migrateFromChatId; } public Integer getForwardFromMessageId() { return forwardFromMessageId; } public boolean isGroupMessage() { return chat.isGroupChat(); } public boolean isUserMessage() { return chat.isUserChat(); } public boolean isChannelMessage() { return chat.isChannelChat(); } public boolean isSuperGroupMessage() { return chat.isSuperGroupChat(); } public Long getChatId() { return chat.getId(); } public boolean hasText() { return text != null && !text.isEmpty(); } public boolean isCommand() { if (hasText() && entities != null) { for (MessageEntity entity : entities) { if (entity != null && entity.getOffset() == 0 && EntityType.BOTCOMMAND.equals(entity.getType())) { return true; } } } return false; } public boolean hasDocument() { return this.document != null; } public boolean hasVideo() { return this.video != null; } public boolean hasAudio(){ return this.audio != null; } public boolean hasVoice(){ return this.voice != null; } public boolean isReply() { return this.replyToMessage != null; } public boolean hasLocation() { return location != null; } public Chat getForwardFromChat() { return forwardFromChat; } public Integer getEditDate() { return editDate; } public Game getGame() { return game; } private boolean hasGame() { return game != null; } public boolean hasEntities() { return entities != null && !entities.isEmpty(); } public boolean hasPhoto() { return photo != null && !photo.isEmpty(); } public boolean hasInvoice() { return invoice != null; } public boolean hasSuccessfulPayment() { return successfulPayment != null; } public boolean hasContact() { return contact != null; } public Invoice getInvoice() { return invoice; } public SuccessfulPayment getSuccessfulPayment() { return successfulPayment; } public VideoNote getVideoNote() { return videoNote; } public boolean hasVideoNote() { return videoNote != null; } public String getAuthorSignature() { return authorSignature; } public String getForwardSignature() { return forwardSignature; } public String getMediaGroupId() { return mediaGroupId; } public String getConnectedWebsite() { return connectedWebsite; } public PassportData getPassportData() { return passportData; } public boolean hasPassportData() { return passportData != null; } public boolean hasAnimation() { return animation != null; } @Override public String toString() { return "Message{" + "messageId=" + messageId + ", from=" + from + ", date=" + date + ", chat=" + chat + ", forwardFrom=" + forwardFrom + ", forwardFromChat=" + forwardFromChat + ", forwardDate=" + forwardDate + ", text='" + text + '\'' + ", entities=" + entities + ", captionEntities=" + captionEntities + ", audio=" + audio + ", document=" + document + ", photo=" + photo + ", sticker=" + sticker + ", video=" + video + ", contact=" + contact + ", location=" + location + ", venue=" + venue + ", pinnedMessage=" + pinnedMessage + ", newChatMembers=" + newChatMembers + ", leftChatMember=" + leftChatMember + ", newChatTitle='" + newChatTitle + '\'' + ", newChatPhoto=" + newChatPhoto + ", deleteChatPhoto=" + deleteChatPhoto + ", groupchatCreated=" + groupchatCreated + ", replyToMessage=" + replyToMessage + ", voice=" + voice + ", caption='" + caption + '\'' + ", superGroupCreated=" + superGroupCreated + ", channelChatCreated=" + channelChatCreated + ", migrateToChatId=" + migrateToChatId + ", migrateFromChatId=" + migrateFromChatId + ", editDate=" + editDate + ", game=" + game + ", forwardFromMessageId=" + forwardFromMessageId + ", invoice=" + invoice + ", successfulPayment=" + successfulPayment + ", videoNote=" + videoNote + ", authorSignature='" + authorSignature + '\'' + ", forwardSignature='" + forwardSignature + '\'' + ", mediaGroupId='" + mediaGroupId + '\'' + ", connectedWebsite='" + connectedWebsite + '\'' + ", passportData=" + passportData + '}'; } }</span></div> </div> </div> </td> </tr><tr class="cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="1299"><td class="group relative min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// TODO : les todos package client; import java.net.MalformedURLException; import java.rmi.AlreadyBoundException; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.UUID; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Set; import commun.ClientInfo; import commun.DejaConnecteException; import commun.IClient; import commun.IHotelDesVentes; import commun.Objet; import commun.PasCreateurException; import commun.PseudoDejaUtiliseException; import commun.SalleDeVenteInfo; import commun.ServeurInfo; import commun.Message; public class Client extends UnicastRemoteObject implements IClient { private static final long serialVersionUID = 1L; private String urlEtPortServeur; private String adresseServeur; public ServeurInfo serveur; public String getAdresseClient() { return myClientInfos.getAdresseClient(); } private IHotelDesVentes hdv=null; private HashMap<UUID, Objet> ventesSuivies; private HashMap<UUID, SalleDeVenteInfo> mapInfosSalles; private HashMap<UUID, List<Message>> listesMessages; public ClientInfo myClientInfos; private UUID idSalleObservee; private String nomSalleObservee; private UUID idObjetObserve; private String nomObjetObserve; public void setIdSalleObservee(UUID idSalleObservee) { this.idSalleObservee = idSalleObservee; } public Client(String nom,String ipServeurSaisi, String portServeurSaisi) throws RemoteException { super(); this.myClientInfos = new ClientInfo(UUID.randomUUID(),nom, "127.0.0.1", "8092"); serveur= new ServeurInfo(ipServeurSaisi,portServeurSaisi); d(serveur.getAdresseServeur()); connexionServeur(); this.ventesSuivies = new HashMap<UUID, Objet>(); } public void connexionServeur() { d("Tentative d'initialisation de hdv à l'adresse:"+serveur.getAdresseServeur()); while(hdv==null) { try { hdv = (IHotelDesVentes) Naming.lookup(serveur.getAdresseServeur()); System.out.println("Connexion au serveur " + serveur.getAdresseServeur() + " reussi."); } catch (Exception e) { System.out.println("Connexion au serveur " + serveur.getAdresseServeur() + " impossible."); } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void connexion () { try { mapInfosSalles = hdv.login(this.myClientInfos); } catch (RemoteException | PseudoDejaUtiliseException | DejaConnecteException e) { e.printStackTrace(); } } public void deconnexion () { try { hdv.logout(myClientInfos); } catch (RemoteException e) { e.printStackTrace(); } // TODO : fermeture de l'application ? } public void nouvelleSoumission(String nom, String description, int prix, UUID idSdv) throws RemoteException { Objet nouveau = new Objet(nom, description, prix,myClientInfos.getNom()); //ajout de l'objet par le hdv try { hdv.ajouterObjet(nouveau, idSdv, getId()); } catch (PasCreateurException e) { e.printStackTrace(); } //print des informations sur l'ajout } public void nouvelleSalle(String nom, String description, float f) throws RemoteException { Objet nouveau = new Objet(nom, description, f,myClientInfos.getNom()); System.out.println(""+myClientInfos.getAdresseClient()+" "+myClientInfos.getNom()+" "+getId()+" "+nouveau+" "+myClientInfos.getNom()+" \n"); hdv.creerSalle(myClientInfos, nouveau, "Salle de "+myClientInfos.getNom()); } public void pingServeur() throws RemoteException { if ( hdv==null) System.out.print("Hdv null : connexion pas effectué\n"); hdv.ping(); } public static void main(String[] argv) { try { //start IHM } catch (Exception e) { e.printStackTrace(); } } public IHotelDesVentes getServeur() { return hdv; } public void setServeur(IHotelDesVentes serveur) { this.hdv = serveur; } // notification au serveur de la fermeture d'une salle par le client public void fermetureSalle(UUID idSDV) { try { hdv.fermerSalle(idSDV, getId()); } catch (PasCreateurException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } } public void rejoindreSalle(UUID idSalle) { try { Objet obj = hdv.rejoindreSalle(idSalle, this.myClientInfos); ventesSuivies.put(idSalle, obj); // TODO : refresh l'IHM pour prendre en compte les modifs } catch (RemoteException e) { e.printStackTrace(); // TODO : affichage d'un message d'erreur par l'IHM } } public HashMap<UUID, Objet> getVentesSuivies() { return ventesSuivies; } @Override public void nouveauMessage(UUID idSalle, Message message) { listesMessages.get(idSalle).add(message); // TODO : refresh l'IHM pour prendre en compte les modifs } @Override public void notifModifObjet(UUID idSalle, Objet objet) { ventesSuivies.put(idSalle, objet); mapInfosSalles.get(idSalle).setObjCourrant(objet); // TODO : refresh l'IHM pour prendre en compte les modifs } @Override public void notifFermetureSalle(UUID idSalle) { ventesSuivies.remove(idSalle); mapInfosSalles.remove(idSalle); // TODO : refresh l'IHM pour prendre en compte les modifs } @Override public void notifNouvelleSalle(UUID idsdv, SalleDeVenteInfo sdvi) { mapInfosSalles.put(idsdv, sdvi); } public UUID getIdSalleObservee() { return this.idSalleObservee; } public HashMap<UUID, SalleDeVenteInfo> getMapInfosSalles() { return mapInfosSalles; } public void setMapInfosSalles(HashMap<UUID, SalleDeVenteInfo> mapInfosSalles) { this.mapInfosSalles = mapInfosSalles; } public SalleDeVenteInfo[] getTabInfosSalles() { if (mapInfosSalles != null) { Collection<SalleDeVenteInfo> vals = mapInfosSalles.values(); SalleDeVenteInfo[] tab = new SalleDeVenteInfo[vals.size()]; int i = 0; for (SalleDeVenteInfo sdvi : vals) { tab[i] = sdvi; ++i; } return tab; } // TODO : lever une exception ? else return new SalleDeVenteInfo[0]; } public SalleDeVenteInfo[] getTabVentesSuivies() { if (ventesSuivies != null) { Set<UUID> keys = ventesSuivies.keySet(); SalleDeVenteInfo[] tab = new SalleDeVenteInfo[keys.size()]; int i = 0; for (UUID idSalle : keys) { tab[i] = mapInfosSalles.get(idSalle); ++i; } return tab; } // TODO : lever une exception ? else return new SalleDeVenteInfo[0]; } public void quitterSalle(UUID idSalleAQuitter) { try { hdv.quitterSalle( getId(),idSalleAQuitter); } catch (RemoteException e) { e.printStackTrace(); } } public UUID getId() { return myClientInfos.getId(); } public String getPortClient() { return myClientInfos.getPort(); } public void setPortClient(String portClient) { myClientInfos.setPort(portClient); } public void bindClient() { Boolean flagRegistreOkay=false; while(!flagRegistreOkay) { try { Registry r = LocateRegistry.getRegistry(Integer.parseInt(serveur.getPort())); if (r==null) { r=LocateRegistry.createRegistry(Integer.parseInt(serveur.getPort())); d("Registre créé au port "+serveur.getPort()); }else { d("Registre trouvé au port "+serveur.getPort()); } flagRegistreOkay=true; } catch (NumberFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (RemoteException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } setPortClient( Integer.toString(Integer.parseInt(getPortClient())+1) ); } d("Tentative de bind à "+getAdresseClient()); try { Naming.bind(getAdresseClient(), this); } catch(AlreadyBoundException alreadyBoundException) { d("LOL:AlreadyBound"); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (RemoteException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } d("bind effectué"); } public static void d(String msg) { System.out.println(msg+"\n"); } }</span></div> </div> </div> </td> </tr></tbody></table> </div> <div class="bg-linear-to-b from-gray-100 to-white dark:from-gray-950 dark:to-gray-900 rounded-b-lg"><hr class="flex-none -translate-y-px border-t border-dashed border-gray-300 bg-white dark:border-gray-700 dark:bg-gray-950"> <nav><ul class="flex select-none items-center justify-between space-x-2 text-gray-700 sm:justify-center py-1 text-center font-mono text-xs "><li><a class="flex items-center rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800 " href="/datasets/sanjaykz/Java-code/viewer/default/train?p=11"><svg class="mr-1.5" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M10 16L20 6l1.4 1.4l-8.6 8.6l8.6 8.6L20 26z" fill="currentColor"></path></svg> Previous</a></li> <li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/sanjaykz/Java-code/viewer/default/train?p=0">1</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 pointer-events-none cursor-default" href="#">...</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/sanjaykz/Java-code/viewer/default/train?p=10">11</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/sanjaykz/Java-code/viewer/default/train?p=11">12</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 bg-gray-50 font-semibold ring-1 ring-inset ring-gray-200 dark:bg-gray-900 dark:text-yellow-500 dark:ring-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/sanjaykz/Java-code/viewer/default/train?p=12">13</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/sanjaykz/Java-code/viewer/default/train?p=13">14</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/sanjaykz/Java-code/viewer/default/train?p=14">15</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 pointer-events-none cursor-default" href="#">...</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/sanjaykz/Java-code/viewer/default/train?p=3463">3,464</a> </li> <li><a class="flex items-center rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800 " href="/datasets/sanjaykz/Java-code/viewer/default/train?p=13">Next <svg class="ml-1.5 transform rotate-180" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M10 16L20 6l1.4 1.4l-8.6 8.6l8.6 8.6L20 26z" fill="currentColor"></path></svg></a></li></ul></nav></div></div> </div></div></div></div></div></div></div> <div class="hidden items-center md:flex"> <div class="mx-1 flex items-center justify-center"> <div class="h-8 w-1 cursor-ew-resize rounded-full bg-gray-200 hover:bg-gray-400 dark:bg-gray-700 dark:hover:bg-gray-600 max-sm:hidden" role="separator"></div></div> <div class="flex h-full flex-col" style="height: calc(100vh - 48px)"><div class="my-4 mr-4 h-full overflow-auto rounded-lg border shadow-lg dark:border-gray-800" style="width: 480px"><div class="flex h-full flex-col"><div class="flex flex-col "> <div class="px-4 md:mt-4"><div class="mb-4 flex justify-end"> <span class="inline-block w-full flex justify-center"><span class="contents"><div class="flex w-full flex-col rounded-lg border-slate-200 bg-white p-2 shadow-md ring-1 ring-slate-200 dark:border-slate-700 dark:bg-slate-800 dark:ring-slate-700"> <div class="mt-0 flex items-start gap-1"><div class="flex items-center rounded-md bg-slate-100 p-2 dark:bg-slate-700"><svg class="size-4 text-gray-700 dark:text-gray-300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 11 11"><path fill="currentColor" d="M4.881 4.182c0 .101-.031.2-.087.283a.5.5 0 0 1-.242.18l-.65.217a1.3 1.3 0 0 0-.484.299 1.3 1.3 0 0 0-.298.484l-.222.639a.46.46 0 0 1-.18.242.5.5 0 0 1-.288.092.5.5 0 0 1-.294-.097.5.5 0 0 1-.175-.242l-.211-.644a1.26 1.26 0 0 0-.299-.48 1.14 1.14 0 0 0-.479-.298L.328 4.64a.48.48 0 0 1-.247-.18.515.515 0 0 1 .247-.758l.644-.21a1.28 1.28 0 0 0 .788-.789l.211-.634a.5.5 0 0 1 .165-.242.5.5 0 0 1 .283-.103.5.5 0 0 1 .294.083c.086.058.152.14.19.237l.217.659a1.28 1.28 0 0 0 .788.788l.644.222a.476.476 0 0 1 .237.18.5.5 0 0 1 .092.288"></path><path fill="currentColor" d="M10.031 7.458a.5.5 0 0 1-.098.314.5.5 0 0 1-.267.196l-.881.293c-.272.09-.519.242-.721.443a1.8 1.8 0 0 0-.443.721l-.31.876a.5.5 0 0 1-.185.263.56.56 0 0 1-.319.098.515.515 0 0 1-.515-.366l-.294-.88a1.8 1.8 0 0 0-.443-.722c-.204-.2-.45-.353-.72-.448l-.881-.288a.57.57 0 0 1-.263-.191.56.56 0 0 1-.014-.64.5.5 0 0 1 .271-.194l.886-.294A1.82 1.82 0 0 0 6.01 5.465l.293-.87a.515.515 0 0 1 .49-.377c.11 0 .219.03.314.088a.56.56 0 0 1 .206.263l.298.896a1.82 1.82 0 0 0 1.175 1.174l.875.31a.5.5 0 0 1 .263.195c.07.09.108.2.108.314"></path><path fill="currentColor" d="M7.775 1.684a.5.5 0 0 0 .088-.262.45.45 0 0 0-.088-.263.5.5 0 0 0-.21-.155L7.24.896a.5.5 0 0 1-.165-.103.5.5 0 0 1-.103-.17l-.108-.33a.5.5 0 0 0-.165-.21A.5.5 0 0 0 6.426 0a.5.5 0 0 0-.252.098.5.5 0 0 0-.145.206l-.108.32a.5.5 0 0 1-.103.17.5.5 0 0 1-.17.102L5.334 1a.45.45 0 0 0-.216.155.5.5 0 0 0-.088.262c0 .094.029.186.083.263a.5.5 0 0 0 .216.16l.32.103q.095.03.164.103a.37.37 0 0 1 .103.165l.108.319c.031.09.088.17.165.227a.56.56 0 0 0 .252.077.42.42 0 0 0 .268-.093.5.5 0 0 0 .15-.2l.113-.325a.43.43 0 0 1 .268-.268l.32-.108a.42.42 0 0 0 .215-.155"></path></svg></div> <div class="flex min-w-0 flex-1"><textarea placeholder="Ask AI to help write your query..." class="max-h-64 min-h-8 w-full resize-none overflow-y-auto border-none bg-transparent py-1 text-sm leading-6 text-slate-700 placeholder-slate-400 [scrollbar-width:thin] focus:ring-0 dark:text-slate-200 dark:placeholder-slate-400" rows="1"></textarea> </div> </div> </div></span> </span></div> <div class="relative flex flex-col rounded-md bg-gray-100 pt-2 dark:bg-gray-800/50"> <div class="flex h-64 items-center justify-center "><svg class="animate-spin text-xs" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 12 12"><path class="opacity-75" fill-rule="evenodd" clip-rule="evenodd" d="M6 0C2.6862 0 0 2.6862 0 6H1.8C1.8 4.88609 2.2425 3.8178 3.03015 3.03015C3.8178 2.2425 4.88609 1.8 6 1.8V0ZM12 6C12 9.3138 9.3138 12 6 12V10.2C7.11391 10.2 8.1822 9.7575 8.96985 8.96985C9.7575 8.1822 10.2 7.11391 10.2 6H12Z" fill="currentColor"></path><path class="opacity-25" fill-rule="evenodd" clip-rule="evenodd" d="M3.03015 8.96985C3.8178 9.7575 4.88609 10.2 6 10.2V12C2.6862 12 0 9.3138 0 6H1.8C1.8 7.11391 2.2425 8.1822 3.03015 8.96985ZM7.60727 2.11971C7.0977 1.90864 6.55155 1.8 6 1.8V0C9.3138 0 12 2.6862 12 6H10.2C10.2 5.44845 10.0914 4.9023 9.88029 4.39273C9.66922 3.88316 9.35985 3.42016 8.96985 3.03015C8.57984 2.64015 8.11684 2.33078 7.60727 2.11971Z" fill="currentColor"></path></svg></div></div> <div class="mt-2 flex flex-col gap-2"><div class="flex items-center justify-between max-sm:text-sm"><div class="flex w-full items-center justify-between gap-4"> <span class="flex flex-shrink-0 items-center gap-1"><span class="font-semibold">Subsets and Splits</span> <span class="inline-block "><span class="contents"><svg class="text-xs text-gray-500 dark:text-gray-400" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M17 22v-8h-4v2h2v6h-3v2h8v-2h-3z" fill="currentColor"></path><path d="M16 8a1.5 1.5 0 1 0 1.5 1.5A1.5 1.5 0 0 0 16 8z" fill="currentColor"></path><path d="M16 30a14 14 0 1 1 14-14a14 14 0 0 1-14 14zm0-26a12 12 0 1 0 12 12A12 12 0 0 0 16 4z" fill="currentColor"></path></svg></span> </span> </span> <div class="ml-4 flex flex-1 items-center justify-end gap-1"> </div></div></div> <div class="relative"> <div class="no-scrollbar flex flex-nowrap gap-1 overflow-x-auto overscroll-x-none"></div> </div></div> <button type="button" class="btn relative mt-2 h-10 w-full overflow-hidden text-sm font-semibold md:text-base" > <span class="relative z-10 flex items-center gap-1.5"> <span>Run Query</span> <span class="shadow-xs ml-2 hidden items-center rounded-sm border bg-white px-0.5 text-xs font-medium text-gray-700 sm:inline-flex">Ctrl+↵</span></span></button></div> <div class="flex flex-col px-2 pb-4"></div></div> <div class="mt-auto pb-4"><div class="flex justify-center"><div class="w-full sm:px-4"><div class="mb-3"><ul class="flex gap-1 text-sm "><li><button class="flex items-center whitespace-nowrap rounded-lg px-2 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-900 dark:hover:text-gray-300">Saved Queries </button> </li><li><button class="flex items-center whitespace-nowrap rounded-lg px-2 bg-black text-white dark:bg-gray-800">Top Community Queries </button> </li></ul></div> <div class="h-48 overflow-y-auto"><div class="flex flex-col gap-2"><div class="flex h-48 flex-col items-center justify-center rounded border border-gray-200 bg-gray-50 p-4 text-center dark:border-gray-700/60 dark:bg-gray-900"><p class="mb-1 font-semibold text-gray-600 dark:text-gray-400">No community queries yet</p> <p class="max-w-xs text-xs text-gray-500 dark:text-gray-400">The top public SQL queries from the community will appear here once available.</p></div></div></div></div></div></div></div></div></div></div> </div></div></div></main> </div> <script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script><script> import("\/front\/build\/kube-4bcc544\/index.js"); window.moonSha = "kube-4bcc544\/"; window.__hf_deferred = {}; </script> <!-- Stripe --> <script> if (["hf.co", "huggingface.co"].includes(window.location.hostname)) { const script = document.createElement("script"); script.src = "https://js.stripe.com/v3/"; script.async = true; document.head.appendChild(script); } </script> </body> </html>